/*** fork_test.c ***/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main() { pid_t pid; printf("xxxxxxxx\n"); pid = fork(); if(-1 == pid) { perror("fork error:"); exit(1); } else if(pid == 0) { printf("I'm child,pid = %u,ppid = %u\n",getpid(),getppid()); } else { printf("I'm parent,pid = %u, ppid = %u\n",getpid(),getppid()); sleep(1); } printf("YYYYYYYYYYY\n"); return 0; }
operation result:
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./fork_test
xxxxxxxx
I'm parent,pid = 2610, ppid = 2558
I'm child,pid = 2611,ppid = 2610
YYYYYYYYYYY
YYYYYYYYYYY
Loop to create N sub-processes:
Create five child process using a for loop:
/*** fork_test.c ***/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main() { int i; pid_t pid; printf("xxxxxxxx\n"); for(i = 0; i < 5; i++) { pid = fork(); if(-1 == pid) { perror("fork error:"); exit(1); } else if(pid == 0) { printf("I'm child,pid = %u,ppid = %u\n",getpid(),getppid()); } else { printf("I'm parent,pid = %u, ppid = %u\n",getpid(),getppid()); sleep(1); } } printf("YYYYYYYYYYY\n"); return 0; }
After running the program has created a sub-process 2 ^ 5-1.
problem analysis:
problem solved:
#include<stdio.h> #include<stdlib.h> #include<unistd.h> int main() { int i; pid_t pid; printf("xxxxxxxx\n"); for(i = 0; i < 5; i++) { pid = fork(); if(pid == 0) { break; } } if(i < 5) { sleep(i); printf("I'm %d child,pid = %u\n",i+1,getpid()); } else { sleep(i); printf("I'm parent\n"); } return 0; }
In a direct break 0 child process pid == out just fine.
operation result:
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ make fork_test
gcc fork_test.c -o fork_test -Wall -g
ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./fork_test
xxxxxxxx
I'm 1 child,pid = 3157
I'm 2 child,pid = 3158
I'm 3 child,pid = 3159
I'm 4 child,pid = 3160
I'm 5 child,pid = 3161
I'm parent