Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is main called twice?

Tags:

c

fork

I've just learnt about fork, and as I understand it the child process starts execution from the call to fork (otherwise fork would be recursive?).

However in this code (ideone link):

int main() {
  printf("%d: Common code1\n", getpid());
  if (fork() != 0) {
    printf("%d: Parent code\n", getpid());
  } else {
    printf("%d: Child code\n", getpid());
  }
  printf("%d: Common code\n", getpid());
}

The output is:

27380: Common code1
27380: Parent code
27380: Common code
27380: Common code1
27383: Child code
27383: Common code

I don't understand why the 4th line is printed? I could understand if it was printed from the child process and fork called main but it's printed from the parent, and fork doesn't call main.

like image 746
Jonathan. Avatar asked Jan 26 '15 10:01

Jonathan.


People also ask

Can we call main method twice?

No you can use main function only once.

Can main method be called twice in Java?

From the above program, we can say that Java can have multiple main methods but with the concept of overloading.

Why is my function being called twice in Python?

They run twice, because they're called twice. You call humanPlay and computerPlay at the bottom of main and call them again in setRules . You call humanPlay() and computerPlay() , then call setRules() which itself calls those two functions.


2 Answers

Good question! I was a little bit confused at first.

When you use printf, the output is buffered. That means that things printed by printf won't be actually flushed to the console until a newline is reached, or even until the program terminates if stdout is redirected.

In this case. the parent PID's stdout buffer is being copied to the child during the fork. Then, both the parent and child write to their buffers before terminating. This results in duplicated data being printed.

Here's an ideone link that includes fflush(stdout); before fork() is called.

like image 102
millinon Avatar answered Sep 25 '22 20:09

millinon


The problem comes from buffering. When stdout is not associated with a terminal, it isn't line buffered. The strings you write are short enough to stay inside the buffer and are only written out once the program terminates. Thus, you first see process 27380 dumping its buffers and then process 27383 dumping its buffers. The line 27380: Common code1 hasn't been flushed out before the fork, so it's in the buffer of both the original and the forked process. Call fflush() right before forking to fix this problem.

like image 25
fuz Avatar answered Sep 22 '22 20:09

fuz