0

I encountered a question to say the result printed out of the program.

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

void func() {
    for (int i = 0; i < 2; ++i) {
        fork();
        printf("-");
    }
}

int main() {
    func();
    return 0;
}

And I expected the result to be "------" (six '-'). Because

  1. Parent process forks, each of them prints a '-'. (2 processes)
  2. The two processes forks, and they all prints out '-'. (4 processes)
  3. Now value of i is 2, loop is over.

So the program should prints 6 characters.

But when I actually run the program, I get 8 characters. What's more strange is that when I run it again it prints 2 characters. Seems the result is random among 2, 4, 6 or 8.

Why the result is uncertain? Is there something related to undefined behaviors? Even if I turned off optimization (-O0), it's still like this.

Qiu Chaofan
  • 105
  • 2
  • 8
  • 2
    Inherits vars and unflushed buffers super-dupe. – Martin James Apr 13 '18 at 09:18
  • Because you need a pipes check this https://stackoverflow.com/questions/8516823/redirecting-output-to-a-file-in-c – Victor Gubin Apr 13 '18 at 09:18
  • I suggest adding two things: print out the pid of the process, and print a newline at the end. Then it will be clearer what the program is doing. – Arndt Jonasson Apr 13 '18 at 09:19
  • Agreeing with @MartinJames, study what happens if you flush the stdout buffer before forking. – Arndt Jonasson Apr 13 '18 at 09:21
  • None of this explains why it would be nondeterministic though. The stdout buffer is part of the process, so it gets forked along with the rest of the state, and presumably buffer flushing is done at predictable moments (e.g. newline). (I can't reproduce this and always see 8 hyphens anyway.) – Thomas Apr 13 '18 at 09:22
  • Thanks for your explanation! Adding newline to flush buffer works. But after using `fflush(stdout)` or `setvbuf(stdout, NULL, _IOBNF, 0)` output is still undeterministic. To test how many child processes created, I use `fprintf(stderr, "%d", getpid()")`, there are 4 processes and printed 6 pids, as expected. While undeterministic number of hyphens is so strange. I tested on a macOS and Linux, both as this. – Qiu Chaofan Apr 13 '18 at 10:06
  • I always get the same number, but sometimes the main program has exited and the shell prompt reappeared before the last output comes from the forked processes. – Arndt Jonasson Apr 13 '18 at 10:43
  • @ArndtJonasson Thanks for your hint! I thought if there is something wrong with my shell (I use zsh with plugins), when I switch to bash, the output is always 8. – Qiu Chaofan Apr 13 '18 at 15:34

0 Answers0