Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: code corrections

...

Code Block
bgColor#FFcccc
char c;
intpid_t 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 == -1) {
  /* Handle error */
}

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

...

This code's output cannot reliably be determined, and therefore should not be used.  Instead, file descriptors should not be passed through a fork() call and should be closed beforehand to prevent this possible error.

...

Compliant code example:

In this compliant code example, the programmer correctly closes the file descriptor before forking and then reopening the file descriptor in each child. In this example the programmer wanted to read the second character of the file twice, but they could have read any number of any character in the file deterministically.

Code Block
bgColor#ccccff
char c;

intpid_t 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 == -1) {
  /* Handle error */
}

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

...