Fork () system call in c

    #include <stdio.h>
    #include <unistd.h>
    int main()
    {
       fork();
       fork() && fork() || fork();
       fork();

     printf("forked\n");
     return 0;
    }

This causes difficulties in understanding how to calculate the number of processes generated after program execution? Help me find out.

Platform --UBUNTU 10.04

+2
source share
5 answers

Let us follow the fork-tree, believing that none of the forks will work

fork();

Now we have two processes, it still does not matter who is the child and which of the parents, name them p1 and p2

fork()

Both of these processes give birth to another child, so we have 4 processes, for two of them (p3, p4) the result is zero, and for the other two (p1 and p2) it is non-zero

   && fork()

p1 p2 fork, p5 p6, . p1 p2 && true, . p3, p4, p5, p6 && false, fork

              || fork();

, , 6 + 4 = 10.

();

10 , 20.

+8
fork();

fork : PID 0 . , -1.

|| && .

, (.. ):

  • || , != 0
  • && , == 0
+3

fork(), . . , , . :

int main() {
    /* code */
    pid_t pid = fork();
    if (pid < 0) {
        /* error, no child process spawned */
    }
    if (pid > 0) {
        /* we are the parent process, pid is the process ID of the ONE child process spawned */
    }
    /* else, we are the child process, running exactly one command later the fork() was called in the parent. */
    /* some more code */
    return 0;
}
+2

, fork-count.c. gcc fork-count.c -o fork-count. ./fork-count | wc -l.

+1

Geeks Geeks:

fork() . fork() , 22 = 4 . 4 . , l fork(), 2l (l + 1). (l + 1).

, fork() 3 . , . 3 23 = 8 , .

C/++:

&& , ||, . , , .

AND (&) , . OR (||) , .

fork():

man fork() ,

" PID , 0. -1, , errno ."

PID unsigned int. , fork() child. . fork(), ,

     #include <stdio.h>
     int main()
      {
       fork(); /* A */
      (       fork()  /* B */ &&
      fork()  /* C */ ) || /* B and C are grouped according to precedence */
      fork(); /* D */
      fork(); /* E */

      printf("forked\n");
      return 0;
     }

enter image description here fork() .

0 . (m ) C1, . .

1 m C1 fork() - B. ( , B, C D & ||). B , .

2 - fork() - B, m C1, m C1 , C2 C3 - .

fork() - B , - . & &, - , C2 C3 (fork() - C). m C1 fork() - C. C2 C3 fork() - D, OR.

3 m, C1, C2, C3 C4, C5 . ((B & C) || D), (B & C) . , - . , B && C || D, fork() - D. (B && C), , fork() - D. , C2 C3 2, fork() - D, .

4 m, C1, C2, C3, C4, C5 C6, C7, C8 C9 . fork() - E .

At level 5, 20 processes will be completed. The program (on Ubuntu Maverick, GCC 4.4.5) printed "forked" 20 times. Once parental root (main) and rest by children. A total of 19 processes will be created.

0
source

All Articles