...
In this example the programmer wishes to open a file, read a character, fork, and then have both parent and child process read the second character of the file independently. However, the fact that both processes share a file descriptor means that one process might get the second character, and one might get the third. Furthermore there is no guarantee the reads are atomic...the processes might get unpredictable results. Independent of what the programmer is trying to accomplish with this code, this code is incorrect because it contains a race condition.
POS01-C. Check for the existence of links when dealing with files
| Code Block | ||
|---|---|---|
| ||
char c;
pid_t pid;
int fd = open(filename, O_RDWR);
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);
}
|
...
| Code Block |
|---|
root process:a child:b parent:b |
...
Risk Assessment
Because race conditions in code are extremely hard to find, this problem might not appear during standard debugging stages of development. However, depending on what file is being read from and how important the order of read operations is, this can be particular dangerous.
...