我用C写了这段代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void random_seed(){
struct timeval tim;
gettimeofday(&tim, NULL);
double t1=tim.tv_sec+(tim.tv_usec/1000000.0);
srand (t1);
}
void main(){
FILE *f;
int i;
int size=100;
char *buf=(char*)malloc(size);
f = fopen("output.txt", "a");
setvbuf (f, buf, _IOFBF, size);
random_seed();
for(i=0; i<200; i++){
fprintf(f, "[ xx - %d - 012345678901234567890123456789 - %d]\n", rand()%10, getpid());
fflush(f);
}
fclose(f);
free(buf);
}
此代码以附加模式打开一个文件并附加 200 次字符串。我设置了可以包含完整字符串的大小为 100 的 buf。然后我使用这个 bash 脚本创建了多个运行这段代码的进程:
#!/bin/bash
gcc source.c
rm output.txt
for i in `seq 1 100`;
do
./a.out &
done
我希望在输出中字符串永远不会混淆,因为我读到当打开带有 O_APPEND 标志的文件时,文件偏移量将在每次写入之前设置为文件末尾,并且我使用的是完全缓冲的流,但我得到每个进程的第一行是这样混合的:
[ xx - [ xx - 7 - 012345678901234567890123456789 - 22545]
后面几行
2 - 012345678901234567890123456789 - 22589]
看起来写入因调用 rand 函数而被中断。
那么......为什么会出现这些线条?防止这种情况的唯一方法是使用文件锁定......即使我只使用附加模式?
提前致谢!