write系统调用将指定的内容写入文件中,但是当多个进程/线程同时write一个文件时是会出现写覆盖的情形。
每个进程都有自己的缓冲区,write首先写入该缓冲区,系统flush后才将缓冲区内容写入文件,从而导致了多个进程之间的写操作是互不可见的,可能出现写覆盖。
程序验证:
#include<sys/types.h>
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
int main(){
int fd=open("1.txt",O_RDWR|O_CREAT,S_IRWXU);
pid_t pid[2];//开启2个子进程
if((pid[0]=fork())<0)
printf("fork error\n");
else if(pid[0]==0){
char* buf="00000 00000\n";//子进程1写入文件的内容
for(int i=0;i<5;i++){
if(write(fd,buf,strlen(buf))<strlen(buf))//写入的字数不够情况忽略
printf("pid[0] write less\n");
}
}
else{
if((pid[1]=fork())<0)
printf("fork 2 error\n");
else if(pid[1]