2

I am studying about system programming system calls. I have a code block in my assignment (given below). The question asks me to how many A,B or C will be printed. My question is what is the meaning of if(pid == 0)? I guess if(pid == 0) means false, so I analyse that 2 x A and 2 x B will be printed. Am I write or? Second question is does pid2 = fork() executes main again?

int main() { int pid,pid2; int i; pid = fork(); printf("A\n"); if (pid == 0) pid2=fork(); if (pid2) printf("B\n"); printf("C\n"); return 0; } 
4
  • pid == 0 means that the current process is the child. Commented Apr 15, 2012 at 19:45
  • 1
    @Aslan986 - Don't you mean the child? Commented Apr 15, 2012 at 19:46
  • Since pid2 initially has an indeterminate value and is never set in the original parent. The original parent may or may not print 'B'. Assuming it is you get ABCABCC though the order may be different depending on which processes gets processor time. Commented Apr 15, 2012 at 20:13
  • If you run this on a heavily loaded system it may just print AC! Commented Apr 15, 2012 at 20:19

5 Answers 5

6

The fork system call is special. You call it once and it returns twice. Once in the child and once in the parent.

In the parent it returns the pid of the child and in the child it returns 0. Thus, if (pid == 0) means "if this is the child".

Sign up to request clarification or add additional context in comments.

Comments

3

fork returns 0 to the child process and the pid of the child to the parent process. The man pages should clear everything else up.

Comments

2

Fork return 2 values:

  • 0 in the child process and a positive value in the parent process.
  • After the fork() call you will have 2 processes (if no error occurs, in which case -1 is returned).

In your example, you create 3 processes and will output 2A, 1B and 3C

Comments

1

pid2 is not initialized in the parent process case. How much B will be printed is undefined behavior.

pid=fork() doesn't execute main() again, hopefully ...

1 Comment

The remark about pid2 being uinitialized is important!
0

he return value of the Fork call returns a different value depending in which proccess you currently are.

Let's say you want some code to be executed in the parent process you would pu that part of the code in this condition block :

p = fork(); if (p > 0) { // We're the parent process } 

And if you want to execute some code in the child process the same would apply :

p = fork(); if (0 == p) { // We're the child process } 

And the rest (executed by both parents process and child) in a else block.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.