APUEセクション8.3fork function
で、親プロセスと子プロセス間のファイル共有について、次の
ように述べています。It is important that the parent and the child share the same file offset.
また、セクション8.9Race Conditions
には、例があります。親と子の両方が、
fork関数を呼び出す前に開かれたファイルに書き込みます。プログラムには競合状態が含まれています。
これは、出力がカーネルによってプロセスが実行される順序と、各プロセスが実行される時間に依存するためです。
しかし、私のテストコードでは、出力が重複しています。
[Langzi @ Freedom apue] $ cat race.out
これは長い長い出力ですこれは、親からの長い長い出力です
親と子が同じオフセットを共有するのではなく、別々のファイルオフセットを持っているようです。
コードにエラーはありますか?それとも、オフセットを共有することの意味を誤解しましたか?
任意のアドバイスや助けをいただければ幸いです。
以下は私のコードです:
#include "apue.h"
#include <fcntl.h>
void charatatime(int fd, char *);
int main()
{
pid_t pid;
int fd;
if ((fd = open("race.out", (O_WRONLY | O_CREAT | O_TRUNC),
S_IRUSR | S_IWUSR)) < 0)
err_sys("open error");
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
charatatime(fd, "this is a long long output from child\n");
else
charatatime(fd, "this is a long long output from parent\n");
exit(0);
}
void charatatime(int fd, char *str)
{
// try to make the two processes switch as often as possible
// to demonstrate the race condition.
// set synchronous flag for fd
set_fl(fd, O_SYNC);
while (*str) {
write(fd, str++, 1);
// make sure the data is write to disk
fdatasync(fd);
}
}