了解来自多个进程的并发文件写入

从这里: Is file append atomic in UNIX

考虑多个进程打开同一文件并附加到其中的情况. O_APPEND保证寻找到文件的末尾然后开始写操作是原子的.因此,只要每个写入大小为< = PIPE_BUF,多个进程就可以附加到同一个文件中,并且任何进程都不会覆盖任何其他进程的写入. 我写了一个测试程序,其中多个进程打开并写入同一个文件(write(2)).我确保每个写入大小都是> PIPE_BUF(4k).我期待看到进程覆盖其他人数据的实例.但那并没有发生.我测试了不同的写入大小.那只是运气还是有理由不这样做?
我的最终目标是了解附加到同一文件的多个进程是否需要协调其写入.

这是完整的计划.每个进程都创建一个int缓冲区,用其排名填充所有值,打开一个文件并写入它.

眼镜:
OpenMPI 1.4.3上
打开11.3 64位

编译为:mpicc -O3 test.c,
运行方式:mpirun -np 8 ./a.out

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int 
main(int argc,char** argv) {
    int rank,size,i,bufsize = 134217728,fd,status = 0,bytes_written,tmp_bytes_written;
    int* buf;
    char* filename = "/tmp/testfile.out";

    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    MPI_Comm_size(MPI_COMM_WORLD,&size);

    buf = (int*) malloc (bufsize * sizeof(int));   
    if(buf == NULL) {
        status = -1;
        perror("Could not malloc");
        goto finalize;
    }
    for(i=0; i<bufsize; i++) 
        buf[i] = rank;

    if(-1 == (fd = open(filename,O_APPEND|O_WRONLY,S_IWUSR))) {
        perror("Cant open file");
        status = -1;
        goto end;
        exit(-1);
    }

    bytes_written = 0;
    if(bufsize != (tmp_bytes_written = write(fd,buf,bufsize))) {
        perror("Error during write");
        printf("ret value: %d\n",tmp_bytes_written);
        status = -1;
        goto close;
    }

close:
    if(-1 == close(fd)) {
        perror("Error during close");
        status = -1;
    }
end:
    free(buf);
finalize:
    MPI_Finalize();
    return status;
}

解决方法

写入小于PIPE_BUF的原子性仅适用于管道和FIFO.对于文件写入,POSIX说:

This volume of POSIX.1-2008 does not specify behavior of concurrent
writes to a file from multiple processes. Applications should use some
form of concurrency control.

…这意味着你自己 – 不同的UNIX喜欢会提供不同的保证.

相关文章

文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...
文章浏览阅读1.8k次,点赞11次,收藏37次。因为自己对决策树...
文章浏览阅读492次。C++ 设计模式之策略模式
文章浏览阅读683次。我也算是个C++的小白,对于C++中的谓语我...
文章浏览阅读225次。又看了一遍操作符的东西,感觉之前对操作...