[APUE] Does the parent and child have the same file offset after fork?

In the APUE 8.3 section fork functionon file sharing between parent and child processes,
He said:It is important that the parent and the child share the same file offset.

And in section 8.9 Race Conditionsthere is an example: both parent and child records are written to a
file that opens before calling the fork function. The program contains a race condition,
because the output depends on the order in which the processes are started by the kernel and how long each process takes.

But in my test code, the output is overlapping.

[Langzi @Freedom apue] $ cat race.out
is a long long output from a parent, this is a long long output from a parent

It seems that the parent and child have separate file offsets instead of using the same offset.

Is there an error in my code? Or did I misunderstand the meaning of the bias exchange?
Any advice and help would be appreciated.

the following is my code:

#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);
 }
}
+5
source share
5 answers

Well, I was wrong.

So they use the bias, but something else strange is going on. If they did not share the offset, you would get a result that would look like this:

this is a long long output from chredt

because everyone started writing at their own offset 0 and promoting the character at a time. They will not begin to contradict what to write to the file until they reach the last word of the sentence, which will end in alternation.

, .

, , , . , , , .

, , .

, , .

, - , , , . , -, , . .

  • A A.offset
  • B B.offset
  • A A.offset
  • A = A.offset + 1
  • B B.offset
  • A A.offset
  • B = B.offset + 1
  • A A.offset
  • A = A.offset + 1
  • B B.offset
  • B B.offset
  • B = B.offset + 1

. .

pread pwrite , - , .

+2

, . , , . , () . . .

(2): " ".

, , ( ) . , (2) ( , (2)), , .

. ( ) , . ( write (2)), , . . (, , stdio) .

+3

, forking ( , ), . , , , , .

+1

, GCC/glibc, :

thhis isias a l long oulout futput frd
 parent

, , , , . , , , 47 . , 38 39 , , 77 - , , , - , , - , .

: man 2 lseek

, , dup (2) fork (2), , .

+1

pwrite, - , (write()) , pos = 0 , , , (fd), , - , , , forking!!

+1

All Articles