Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
char c;
int pid;

int fd = open(filename,O_RDWR,0);
if (fd == -1) {
  /* Handle error */
}
read(fd,&c,1);
printf("root process:%c\n",c);

pid = fork();

if(pid == 0){/*child*/
      read(fd,&c,1);
      printf("child:%c\n",c);
}else{ /*parent*/
      read(fd,&c,1);
      printf("parent:%c\n",c);
}

...

Code Block
bgColor#ccccff
char c;

int pid;


int fd = open(filename,O_RDWR,0);
if (fd == -1) {
  /* Handle error */
}
read(fd,&c,1);
printf("root process:%c\n",c);

close(fd);

pid = fork();

if(pid == 0){/*child*/
      fd = open(filename,O_RDONLY,0);
      read(fd,&c,1);
      read(fd,&c,1);
      printf("child:%c\n",c);
;  close(fd);
}else{ /*parent*/
      fd = open(filename,O_RDWR,0);
      read(fd,&c,1);
      read(fd,&c,1);
      printf("parent:%c\n",c);
  close(fd);
}

The output of this code is :
root process:a
child:b
parent:b

Because file descriptors access files in a sequential manner, the order in which the parent and child run can affect the order of access to the file, and because file descriptors are shared across multiple processes, this allows multiple processes to read/write from a file concurrently in a semi-random order. 

References

POS32-C When data must be accessed by multiple threads, provide a mutex and guarantee no adjacent data is also accessed.