/******************************************************************************************************************
Reference resources: http://blog.sina.com.cn/s/blog_605f5b4f0100x444.html
Note: precautions for fork to create multiple subprocesses at the same time in linux.
******************************************************************************************************************/
It's an experiment, but it's good to have a network. Otherwise, many problems that you can't solve by yourself can't be solved. I first wrote a program to create multiple subprocesses (imitating the program to create a process in the book):
#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <stdlib.h>int main(void){ pid_t childpid1, childpid2, childpid3; int status; int num; childpid1 = fork(); childpid2 = fork(); childpid3 = fork(); if( (-1 == childpid1)||(-1 == childpid2)||(-1 == childpid3)) { perror("fork()"); exit(EXIT_FAILURE); } else if(0 == childpid1) { printf("In child1 process\n"); printf("\tchild pid = %d\n", getpid()); exit(EXIT_SUCCESS); } else if(0 == childpid2) { printf("In child2 processd\n"); printf("\tchild pid = %d\n", getpid()); exit(EXIT_SUCCESS); } else if(0 == childpid3) { printf("In child3 process\n"); printf("\tchild pid = %d\n", getpid()); exit(EXIT_SUCCESS); } else { wait(NULL); puts("in parent"); // printf("\tparent pid = %d\n", getpid()); // printf("\tparent ppid = %d\n", getppid()); // printf("\tchild process exited with status %d \n", status); } exit(EXIT_SUCCESS); }
The result is two zombies. I don't know how to figure them out. Finally, I found the answer on the Internet. And back and forth to figure out the methods and precautions:
#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <stdlib.h>int main(void){ pid_t childpid1, childpid2, childpid3; int status; int num; /* You can't create a subprocess in a moment. You need to use * to create -] to judge -] to use -] to return or exit. Let alone test 2. C * childpid1 = fork(); * childpid2 = fork(); * childpid3 = fork()*/ childpid1 = fork(); //Establish if(0 == childpid1) //judge { //Get into printf("In child1 process\n"); printf("\tchild pid = %d\n", getpid()); exit(EXIT_SUCCESS); //Sign out } childpid2 = fork(); if(0 == childpid2) { printf("In child2 processd\n"); printf("\tchild pid = %d\n", getpid()); exit(EXIT_SUCCESS); } childpid3 = fork(); if(0 == childpid3) { printf("In child3 process\n"); printf("\tchild pid = %d\n", getpid()); exit(EXIT_SUCCESS); } //wait(NULL) is not allowed here. Multiple subprocesses cannot wait with wait. It will only wait for one other to become a zombie waitpid(childpid1, NULL, 0); waitpid(childpid2, NULL, 0); waitpid(childpid3, NULL, 0); puts("in parent"); exit(EXIT_SUCCESS); }
By doing so strictly, there will be no zombies and no other process will be affected.
Create > judge > use > return or exit