简体   繁体   中英

Read one line from file while rewriting that line from other process. C

so I used to use named pipes for IPC but then I lost the first value sent from one process because the other process wasn't started yet. So then I went over to using a file with only one line as middle storage.

So the file is being updated when my application is writing to it. Here's the code for that:

dmHubRead = fopen ("/tmp/file", "w");
if (!dmHubRead) {
        log_error ("can't create /tmp/file: %m");
        return 0;
    }

fprintf (dmHubRead,
     "value %02d:%02d:%02d;\n",
     t->x, t->y, t->z);

fflush (dmHubRead);
fclose(dmHubRead);

My other program is then opening the file and wants to read the first line pretty often. This program does not close the file between the reads. Here is the code for that program:

if ((_file = fopen(FILE_PATH, "r")) < 0) {
        DebugLogger::put(DebugLogger::Error, "Could not open file.", __FILE__, __LINE__);
}
...
size_t sz = 0;
char *line = NULL;

if(fsync(fileno(_file)) < 0) {
  perror("fsync");
}

rewind(_file);
getline(&line, &sz, _file);

So my problem is that this does not work. Does the fopen in the writing part creates a new file each time? Or what is the problem and how can it be solved?

Your "writing" side is creating a new file each time it runs. The reading side fails because the file handle becomes invalid each time you write a new file. If you re-open the file each time you access it, your code should work. As Joachim mentioned, there are more elegant ways to do this. You haven't mentioned what system you're running on. Depending on if it's Windows, Linux or some other OS, there are better mechanisms to do IPC. You also have the issue of synchronization. Can your read ever occur between the time the new file is opened and the data is written? How about using sockets? That way you can tell if there is new data waiting as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM