我在Linux平台上有一个应用程序,它需要服务器程序不断地将数据写入bin文件。同时,另一个程序需要读取写入的值。如果我在读写过程中没有锁定文件,我应该担心吗?
发布于 2013-07-04 05:20:04
发布于 2013-07-04 06:21:56
一切都取决于你的需求是什么?可以修改服务器进程吗?如果是这样的话,你有无限的可能性。这是一个研究得很好的问题,进程间通信,wikipedia IPC。
否则,在我自己的测试程序中,似乎不需要锁定来让生产者和消费者对同一文件进行操作。这只是轶事证据,我不能保证。
制片人:
int main() {
int fd = open("file", O_WRONLY | O_APPEND);
const char * str = "str";
const int str_len = strlen(str);
int sum = 0;
while (1) {
sum += write(fd, str, str_len);
printf("%d\n", sum);
}
close(fd);
}
消费者:
int main() {
int fd = open("file", O_RDONLY);
char buf[10];
const int buf_size = sizeof(buf);
int sum = 0;
while (1) {
sum += read(fd, buf, buf_size);
printf("%d\n", sum);
}
close(fd);
}
(include:) #include #include #include
这个程序假设"file“已经存在。
发布于 2013-07-04 07:17:10
为了补充这里已经说过的内容,请查看您的操作系统文档。原则上,在读取时应该没有问题,如果读取是原子的(即在操作过程中没有任务切换),应该是可以的。另外,操作系统可能有自己的限制和锁,所以要小心。
https://stackoverflow.com/questions/17462309
复制