linux - How do 2 or more fork system calls work? -


here's code use 2 fork() system calls 1 after - how work?

 #include <unistd.h>  #include <iostream.h>  using namespace std;   int main()  {     cout << "0. process " << getpid() << endl;     (void) fork();     cout << "1. process " << getpid() << endl;     (void) fork();     cout << "2. process " << getpid() << endl; } 

i output :
0. process 27701
1. process 25915
1. process 27701
2. process 27781
2. process 26170
2. process 27701

this next program i've used 3 fork system calls, how such output? if solve code manually, logic?

#include <unistd.h> #include <iostream> using namespace std;  int main() {     cout << "0. process " << getpid() << endl;     (void) fork();     cout << "1. process " << getpid() << endl;     (void) fork();     cout << "2. process " << getpid() << endl;     (void) fork();     cout << "3. process " << getpid() << endl; } 

here output :
0. process 27116
1. process 26147
2. process 27371
2. process 26147
3. process 24416
3. process 27371
3. process 27508
3. process 26147
1. process 27116
2. process 21406
2. process 27116
3. process 27369
3. process 21406
3. process 26752
3. process 27116

your program utterly wrong. should never ignore result of fork.

read advanced linux programming book , fork(2) man page (read page several times , carefully).

typical code should be:

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

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

in principle have 33 i.e. 27 possibilities. handle failure case, leaves 23 i.e. 8. possibilities

don't forget handle failure of fork. might lower process limit (with setrlimit(2) using rlimit_nproc or equivalent ulimit bash builtin) ease test of fork failure.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -