0

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?

  • 8
    Your OS is scheduling the new process to run before resuming the old one after it calls fork. You can't depend on that behavior. – Shawn Feb 16 '23 at 09:10
  • Possible duplicate of https://stackoverflow.com/questions/8494732/who-executes-first-after-fork-parent-or-the-child – dimich Feb 16 '23 at 17:54

1 Answers1

1

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).

Allan Wind
  • 23,068
  • 5
  • 28
  • 38