How do 2 or more fork system calls work?

后端 未结 4 414
天命终不由人
天命终不由人 2020-12-12 06:58

Here\'s a code where I use 2 fork() system calls one after another - How does it actually work?

 #include 
 #include 
 usi         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 07:51

    Your program is utterly wrong. You should never ignore the result of fork.

    Read the Advanced Linux programming book and the fork(2) man page (read that page several times and carefully).

    Typical code should be:

      pid_t pid1 = fork();
      if (pid1<0) { perror("fork1 failed"); exit(EXIT_FAILURE); }
      else if (pid1 == 0) {
         // you are in the child process
      }
      else // pid1>0 
      {  // you are in the parent process
      }
    

    And likewise for pid_t pid2=fork(); and then for pid_t pid3=fork(); etc.... So each call to fork should handle the 3 cases of result of fork (failure i.e. <0, child process ==0, parent process >0)

    In principle you have 33 i.e. 27 possibilities. But you could handle early the failure case, which leaves 23 i.e. 8. possibilities

    Don't forget to handle the failure of fork. You might lower your process limit (with setrlimit(2) using RLIMIT_NPROC or the equivalent ulimit bash builtin) to ease the test of fork failure.

提交回复
热议问题