0

I am using Ubuntu 18.04. I am currently doing a course on Operating Systems and was just getting used to fork() and exec() calls.

I am running the following C program

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, char *argv[])
{
    printf("hello world (pid:%d)\n", (int) getpid());
    int rc = fork();
    if (rc < 0) {
        // fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) {
        // child (new process)
        printf("hello, I am child (pid:%d)\n", (int) getpid());
    } else {
        // parent goes down this path (original process)
        printf("hello, I am parent of %d (pid:%d)\n",
           rc, (int) getpid());
    }
    return 0;
}

On running the code in Sublime Text Editor with the build file

{
"cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path"
}

I get the result

hello world (pid:16449)
hello, I am parent of 16450 (pid:16449)
hello world (pid:16449)
hello, I am child (pid:16450)

Whereas if I use the terminal and run the same code using gcc,

I get

hello world (pid:17531)
hello, I am parent of 17532 (pid:17531)
hello, I am child (pid:17532)

Now I know that the latter is the correct whereas the output I get in Sublime is the wrong one. How can the outputs when the compiler I am using remains the same can be different?

  • 1
    This might be a dup of [printf anomaly after “fork()”](https://stackoverflow.com/questions/2530663/printf-anomaly-after-fork), if your IDE runs a process using pipes instead of the terminal. Can you try this? Before the `fork`, please add the line `printf("isatty %d\n", isatty(1));` and tell us if it prints out the same number (1 or 0) under the two environments. – Mark Plotnick Feb 25 '21 at 18:20
  • Yes the output is different when I insert this statement. The IDE one prints 0 whereas the terminal one prints 1. Thanks for the answer that you linked. I used `fflush(stdout)` before forking and now output are similar. Do you know of any other alternative to using `fflush(stdout)` before every `fork()` call? – shubh gupta Feb 26 '21 at 14:50
  • 1
    Calling fflush before fork is best practice. Almost as good is to call setvbuf on each output stream to make sure the output is line-buffered. I don't know how to make Sublime use a terminal instead of pipes. – Mark Plotnick Feb 26 '21 at 17:09

0 Answers0