我试图在写入文件时模拟比赛条件。这就是我在做什么。
但是,对process1的写入正在写入文件的末尾,并且在各进程之间的写入没有争用。
我正在使用fopen作为
fopen("./a.txt", "a+)
谁能说出这种现象的原因,以及如何在写入文件时模拟竞争条件?
process1的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include "time.h"
using namespace std;
int main()
{
FILE *f1= fopen("./a.txt","a+");
cout<<"opened file1"<<endl;
string data ("hello world");
fwrite(data.c_str(), sizeof(char), data.size(), f1);
fflush(f1);
cout<<"file1 tell "<<ftell(f1)<<endl;
cout<<"wrote file1"<<endl;
sleep(3);
string data1 ("bye world");;
cout<<"wrote file1 end"<<endl;
cout<<"file1 2nd tell "<<ftell(f1)<<endl;
fwrite(data1.c_str(), sizeof(char), data1.size(), f1);
cout<<"file1 2nd tell "<<ftell(f1)<<endl;
fflush(f1);
return 0;
}
在process2中,我已注释掉
sleep
语句。我正在使用以下脚本来运行:
./process1 &
sleep 2
./process2 &
谢谢你的时间。
最佳答案
编写者代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLOCKSIZE 1000000
int main(int argc, char **argv)
{
FILE *f = fopen("a.txt", "a+");
char *block = malloc(BLOCKSIZE);
if (argc < 2)
{
fprintf(stderr, "need argument\n");
}
memset(block, argv[1][0], BLOCKSIZE);
for(int i = 0; i < 3000; i++)
{
fwrite(block, sizeof(char), BLOCKSIZE, f);
}
fclose(f);
}
阅读器功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLOCKSIZE 1000000
int main(int argc, char **argv)
{
FILE *f = fopen("a.txt", "r");
int c;
int oldc = 0;
int rl = 0;
while((c = fgetc(f)) != EOF)
{
if (c != oldc)
{
if (rl)
{
printf("Got %d of %c\n", rl, oldc);
}
oldc = c;
rl = 0;
}
rl++;
}
fclose(f);
}
我先运行
./writefile A & ./writefile B
,然后再运行./readfile
我懂了:
Got 1000999424 of A
Got 999424 of B
Got 999424 of A
Got 4096 of B
Got 4096 of A
Got 995328 of B
Got 995328 of A
Got 4096 of B
Got 4096 of A
Got 995328 of B
Got 995328 of A
Got 4096 of B
Got 4096 of A
Got 995328 of B
Got 995328 of A
Got 4096 of B
Got 4096 of A
Got 995328 of B
Got 995328 of A
Got 4096 of B
Got 4096 of A
Got 995328 of B
Got 995328 of A
如您所见,A和B的长距离运行不错,但它们的长度不完全是1000000个字符,这就是我写的大小。经过第一次试运行之后,整个文件的大小较小,只有7GB。
供引用:Fedora Core 16,在lvm,AMD PhenomII四核处理器,16GB RAM之上具有我自己编译的3.7rc5内核,gcc 4.6.3,x86-64和ext4
关于c++ - 在C++中运行fwrite,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13999138/