简体   繁体   English

从文件读取一行,而从其他进程重写该行。 C

[英]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. 因此我曾经使用IPC的命名管道,但后来我丢失了一个进程发送的第一个值,因为另一个进程尚未启动。 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? 书写部分中的fopen是否每次都会创建一个新文件? 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. 正如Joachim所提到的,有更优雅的方法可以做到这一点。 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. 根据是Windows,Linux还是其他操作系统,有更好的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. 这样,您就可以判断是否还有新数据在等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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