写入文件时都会调用函数 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!)