多进程/多线程同时向一个文件中写入日志如何避免冲突?

写入文件时都会调用函数 write,由于所有的系统调用都是原子的,所以该函数可以保证进程或者线程写入数据的过程中不会被其他进程或者线程打扰,即:数据中间插入别的进程的数据。

另外一个问题,由于 write 之前需要指定写入位置,即:lseek 函数,同样,该函数也是原子的。

整体来说,在一个写入数据的操作如下:

lseek(fd, 0, SEEK_END); // seek to the end of the file

write(fd, "log message", len); // perform the write

but,这两个函数需要依次完成,中间不能被别的进程或者线程插入写入它们的数据,也就是说为了保证多进程或者多线程同时向一个文件中写入数据时能够避免冲突,需要上述两个函数的执行是事务性的。

为了解决这个问题,可以用标志位 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!)

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值