2

I'm learning about kernel modules communicating with user level programs and originally was opening a file with

FILE *pFile = fopen(...)

and writing to it with

char *str = malloc(10);
fputs(str, pFile);

However now I need to use functionality in #include <fcntl.h> to attempt some asynchronous notifications and the example I have instead uses

int pFile;
pFile = open("/dev/mymodule", O_RDWR);

I think that I can no longer use fputs() or fgets() because it requires a FILE *ptr and I have an int instead now. I think I'm supposed to use write() and read() instead.

Is this how it would work?

write(pFile, str,  sizeof(str));

char line[256];
    while (read(pFile, line, 256) != NULL) {
            printf("%s", line);
        }
Austin
  • 6,921
  • 12
  • 73
  • 138

1 Answers1

5

You can open a FILE* based on the file descriptor with fdopen():

FILE *file = fdopen(pfile, "rw");

Reference: fdopen - associate a stream with a file descriptor

  • does this allow me to use fputs/fgets and things like: `fcntl(pFile, F_SETOWN, getpid()); filp->f_owner oflags = fcntl(pFile, F_GETFL); fcntl(pFile, F_SETFL, oflags | FASYNC);` ? – Austin Mar 18 '16 at 15:55
  • 3
    You can use `fgets()` and `fputs()` on the `FILE*` and `fcntl()` on the `int`. Just don't mix reading and writing the `FILE*` with reading and writing the `int`, as the `FILE*` is buffered and the `int` isn't, so things will get out of sync. –  Mar 18 '16 at 15:58