从这里: 是文件中的UNIX追加原子
假设在多个进程打开相同的文件,并追加到它的情况下。 O_APPEND保证寻求文件的末尾,然后开始写操作是原子。 所以多个进程可附加到相同的文件,没有过程将尽量覆盖任何其他进程的写,因为每个写大小是<= PIPE_BUF。
我写了一个测试程序,其中多个进程打开并写入同一个文件( write(2)
我要确保每个写大小> PIPE_BUF(4K)。 我原以为会看到一个过程覆盖别人的数据实例。 但是,这并不发生。 我用不同的写大小进行测试。 那是只是运气或者是有一个原因,它不会发生呢? 我的最终目标是要了解,如果多个进程附加到同一个文件需要协调他们写。
下面是完整的程序。 每个进程创建一个int缓冲区,以其充满所有值rank
,打开一个文件,并把它。
规格:1.4.3的openmpi在openSUSE 11.3 64位
编译为:mpicc -O3 test.c的,运行如下:-np的mpirun 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;
}