I think the key is to read about the return value of fork() in the man pages\
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
I'm no *nix expert, or even novice, if I were to guess I'd say Sun will get printed 4 times and Solaris one time.
First note that the return values of the first three forks do not matter - you assign each of them to ret, but then you overwrite them right afterwards without using them. So you can simplify the code by writing it as:
ret = fork();
Now if you understand the fundamentals of fork, you know that each fork creates a new process and the control flow in that process starts right after that call to fork. So after the first fork you have two processes and each of them will then execute the second call to fork. Both of those calls will create another process. So you now have two new processes, making a total of four. Now those four processes all execute the third fork and so on...
@sepp2k you have made it so simple. i got it. i am explaining, tell me i am right or wrong. at first fork(), one process--> this make it 2 processes. now next statement is food for 2 processes now. now that 2 will be divided into 4. so like this last statement will be executed by 8 process which will make them 16 processes. so that if-else statements will be executed 16 times. out of which 8 are parent and 8 are children. so 8 are non-zero, 8 are zeros. so 8 times solaris will be printed.
am i right 100% ? if i am wrong at any point, please correct me. secodnly, explain me why is it neccasary to fflush the streams ? thanks.
explain me why is it neccasary to fflush the streams ?
When I run your code without flushing or adding newlines, I get a different amount of output every time I run it.
To be honest I'm not sure why anymore. I wanted to say that forking while there's still output in the buffer, will give the forked process a copy of the buffer, leading to duplicated output. That's true, but your code only prints after forking, so that shouldn't be a problem here (also the problem is that I (sometimes) get too little output when I run your code - not too much).