ファイルへの書き込みで競合状態をシミュレートしようとしています。これが私がやっていることです。
- process1 の追加モードで a.txt を開く
- process1 で「hello world」を書く
- 11 であるプロセス 1 の ftell を出力します。
- プロセス 1 をスリープ状態にする
- process2 の追加モードで a.txt を再度開きます
- process2 に「hello world」を書き込む (これはファイルの最後に正しく追加されます)
- 22 であるプロセス 2 の ftell を出力します (正しい)
- process2 に「bye world」と書き込みます (これはファイルの最後に正しく追加されます)。
- プロセス 2 が終了します
- process1 が再開し、その ftell 値である 11 を出力します。
- process1 で「bye world」を書き込む --- process1 の ftell が 11 であるため、ファイルが上書きされるはずです。
ただし、プロセス 1 の書き込みはファイルの末尾への書き込みであり、プロセス間での書き込みの競合はありません。
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 &
御時間ありがとうございます。