多进程/多线程同时向一个文件中写入日志如何避免冲突?
生活随笔
收集整理的這篇文章主要介紹了
多进程/多线程同时向一个文件中写入日志如何避免冲突?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫入文件時都會調用函數 write,由于所有的系統調用都是原子的,所以該函數可以保證進程或者線程寫入數據的過程中不會被其他進程或者線程打擾,即:數據中間插入別的進程的數據。
另外一個問題,由于 write 之前需要指定寫入位置,即:lseek 函數,同樣,該函數也是原子的。
整體來說,在一個寫入數據的操作如下:
lseek(fd, 0, SEEK_END); // seek to the end of the filewrite(fd, "log message", len); // perform the writebut,這兩個函數需要依次完成,中間不能被別的進程或者線程插入寫入它們的數據,也就是說為了保證多進程或者多線程同時向一個文件中寫入數據時能夠避免沖突,需要上述兩個函數的執行是事務性的。
為了解決這個問題,可以用標志位 O_APPEND,其含義是在每次打開文件時,都將標志位移動到文件的末端,這個過程時原子的。
#include <stdio.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h>int main() {char *filename = "my_data.txt";int fd = open(filename, O_WRONLY | O_CREAT);pid_t pid = fork();if (0 == pid){printf("this is child: %ld\n", (long)getpid());char buf[20];memset(buf, 'D', sizeof(buf));int fd = open(filename, O_WRONLY | O_CREAT | O_APPEND);write(fd, buf, sizeof(buf));close(fd);}else{printf("this is father: %ld\n", (long)getpid());char buf[30] = {2};memset(buf, 'A', sizeof(buf));buf[29] = '_';int fd = open(filename, O_WRONLY | O_CREAT | O_APPEND);write(fd, buf, sizeof(buf));close(fd);int status;wait(&status);}return 0; }結果:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAA_DDDDDDDDDDDDDDDDDDDD?
(SAW:Game Over!)
?
總結
以上是生活随笔為你收集整理的多进程/多线程同时向一个文件中写入日志如何避免冲突?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络安全 / crt、pem、pfx、
- 下一篇: 用 openssl 生成 SSL 使用的