-2

How many proccesses are created with these fork functions?

int main(){
    c2=0;
    c1=fork();
    if(c1==0)
       c2=fork();
    fork();
    if(c2>0)
    fork();
}

In this site,I have seen before questions related fork functions but this one is different. Here we have c1, c2 what does these variables mean?

user119949
  • 101
  • 1
  • 9
  • 2
    Why not just try it? – Martin James Nov 09 '14 at 11:56
  • I tried thats why I asked. – user119949 Nov 09 '14 at 12:28
  • Why minus - ?? I can not understand you. Not knowing is a crime? – user119949 Nov 09 '14 at 12:37
  • 1
    Existing questions like [this one](http://stackoverflow.com/questions/12881111/output-of-fork-calls) and [this one](http://stackoverflow.com/questions/11132868/fork-branches-more-than-expected) (and others you can find by seaching "c fork", and also fork's man page) explain what fork does. Your code here is incomplete and won't compile. `c1` and `c2` are not declared. If you look at fork documentation and at the other questions, you will see what fork returns, what type you can declare c1 and c2 as, and what values they will take when the program runs. – Leiaz Nov 09 '14 at 12:45
  • I copied just my teacher's notes in the lecture. In fact I am aware of c1 and c2 must have a type, I know C language. My teacher didn't write their types and question is that. In fact I have answer I can upload here. Finally, I couln't understand altough teacher solved this problem when quesiton was that. – user119949 Nov 09 '14 at 18:42
  • No, Admins You are completely wrong!(according to my teacher's solution) What is your purpose here? to be part of problem or solution? I understood this question(When I looked solution again) and I can clearly say that it's different from all questions in this web-site. There is no question which contains two variables(variables with fork function) in this site. I searched too here, I couldn't see like this question. All of questions have 1 or no variable. Shame on you. – user119949 Nov 10 '14 at 15:58

2 Answers2

1

The way you need to approach this problem is to draw out a tree. The combination of fork () calls will create a tree of processes with parent/child relationships.

The piece you need to take into account is that fork () returns the PID in the parent process and 0 in the child process. Where you have

 if (cm > 0)
    ford () ;

will only be executed in the parent process.

   if (cn == 0)
      fork () ; 

will only be executed in the child process.

user3344003
  • 20,574
  • 3
  • 26
  • 62
0

I don't think the question merits downvoting.

c2 = 0;
   c1 = fork();      /* fork number 1 */
   if (c1 == 0)
      c2 = fork();   /* fork number 2 */
   fork();           /* fork number 3 */
   if (c2 > 0)
      fork();        /* fork number 4 */

Its diagram is,

enter image description here