Question

Suppose I have this code:

int main () {

    int i, r;
    i = 5;
    printf("%d\n", i);
    r = fork();
    if (r > 0) {
        i = 6;
    }
    else if (r == 0) {
        i = 4;
    }
    printf("%d\n", i);
    }

I was wondering does the forked child process start executing either from the beginning or from where it was called. The reason I ask this is because on my own system I get the output 5,6,4 which means that is starts from where it is called but typing it in http://ideone.com/rHppMp I get 5,6,5,4?

Was it helpful?

Solution

One process calls fork, two processes return (errors notwithstanding). That's how it works. So the child starts from the next "line" (technically it starts with the assignment to r).

What you're seeing here has to do with buffering. In the online case, you'll find that it's using full buffering for standard output, meaning the initial 5 hasn't yet been flushed to the output device.

Hence, at the fork, both parent and child have it and both will flush at some point.

For the line buffered case, the parent flushes on the newline so the line is no longer in the buffer at the fork.

The rules are explicit. Standard output is set to line buffered only if the output device is known to be a terminal. In cases where you redirect to a file, or catch the output in an online environment so you can sanitise it for browser output, it'll be fully buffered.

Hence why you're seeing a difference.

It's generally a good idea to flush all output handles (with fflush) before forking.

OTHER TIPS

You can't judge either parent will execute first or child, in most of the cases child executes. The output should not be "5 6 5 4" might be some garbage value from buffer. You can use fflush(NULL) to flush of the buffer before fork() and try again.

Generally, your application (with its two process threads) has little to no control over how the process threads are organized on the run-queue of your OS. After fork(), there is no specific order you should expect. In fact, if your OS supports multiple CPUs, the may actually both run at the same time; which can result in some unexpected output as both processes compete for stdout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top