2

I want to read a linked list created by a kernel module via the /proc file system. My user space program will contain a fopen() call to open /proc/file1 for read and will use a while loop to execute fread() to read a node from the linked list in every loop.

The user space program contains:

 char buffer[100];
 FILE* fp = fopen("/proc/file1","r");
 while(fread(buffer,sizeof(char),100,fp)){
      printf("%s",buffer);
      // buffer is cleared before next iteration
 }
 fclose(fp);

The kernel module creates a linked list where in every node is of type

 struct node{
     int data;
     struct node* next;
 }

The linked list starting node address is stored in a variable called LIST.

I wrote the following code for read_proc in the kernel module:

  int read_func(char *page,char **start,off_t off,int count,int *eof, void* data)
  {
        static struct node* ptr = NULL;
        static int flag = 0;
        int len;

        if(flag == 0){
               flag = 1;
               ptr = LIST;
        }

        if(ptr == NULL){
               // empty linked list or end of traversal
               *eof = 1;
               flag = 0;
               return 0;
        }

        if(ptr != NULL){
               len = sprintf(page, "%d", ptr->data);
               ptr = ptr->next;
        }
        return len;
  }

On executing the user space program, only one node is read when the linked list contains two or more nodes.

Can anyone please help.

Thank you.

Jake
  • 16,329
  • 50
  • 126
  • 202
  • Can you provide more information like a hexdump of `/proc/file1`? – Niklas B. Feb 15 '12 at 01:16
  • A small note about your `printf` in your user code snippet: Unless the read buffer contains a zero (character `'\0'`) if will print garbage after the buffer. Get the returned size from `read` and terminate the buffer properly. – Some programmer dude Feb 15 '12 at 06:41

1 Answers1

1

You are requesting to read 100 bytes of data and in your read_func() you are returning less than 100. As I said in your previous post, Unable to understand working of read_proc in Linux kernel module

this function will be called by the kernel again and again until count reach 0, that means to read 100 bytes of data.

Basically you want to return data like records, So you need to set eof to 1 before you return the read_func().Note that start must be set as explained in the previous post.

Community
  • 1
  • 1