printf在Linux上使用线程安全写入stdout ?使用低级write命令怎么样?
从这里:文件是否在UNIX中附加原子
考虑多个进程打开同一文件并附加到其中的情况.O_APPEND保证寻找到文件的末尾然后开始写操作是原子的.因此,只要每个写入大小<= PIPE_BUF,多个进程就可以附加到同一个文件中,并且任何进程都不会覆盖任何其他进程的写入.
我编写了一个测试程序,其中多个进程打开并写入同一个文件(write(2)).我确保每个写入大小> PIPE_BUF(4k).我期待看到进程覆盖其他人数据的实例.但那并没有发生.我测试了不同的写入大小.那只是运气还是有理由不这样做?我的最终目标是了解附加到同一文件的多个进程是否需要协调其写入.
这是完整的计划.每个进程都创建一个int缓冲区,用它填充所有值rank,打开一个文件并写入它.
规格:Opensuse 11.3 64位的OpenMPI 1.4.3
编译为: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; …Run Code Online (Sandbox Code Playgroud)