Issue
I have a homework question:
Q7: After executing the following code, a new file named myFile.txt is generated. Is the content in myFile.txt will be consistent? Why? And here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
printf("hello world (pid:%d)\n", (int)getpid());
int fd = open("myFile.txt", O_CREAT|O_RDWR);
if(fd == -1 ) {
printf("Unable to open the file\n exiting....\n");
return 0;
}
int rc = fork();
if (rc < 0) {
fprintf(stderr, "fork failed\n");
exit(1);
}
else if (rc == 0) {
printf("hello, I am child (pid:%d)\n", (int)getpid());
char myChar='a';
write(fd, &myChar,1);
printf("writing a character to the file from child\n");
}
else {
printf("hello, I am parent of %d (pid:%d)\n",
rc, (int)getpid());
char myChar='b';
write(fd, &myChar,1);
printf("writing a character to the file from parent\n");
}
return 0;
}
The parent will write "a" into myFile.txt while the child writes "b" into that file. I executed this program several times, finding the txt file consistent being "ba", meaning that the parent always comes after the child. However, I noticed that there's no wait() function called by the parent process. Can someone explain why the parent comes after the child?
Solution
The order of concurrent tasks are implementation defined by the OS. You need to use synchronization primitives to ensure a well defined order of actions if required (file locks, pipes, mutex, condition variables, semaphores etc).
Answered By - Allan Wind Answer Checked By - Robin (WPSolving Admin)