fork more than once subProcess
阿新 • • 發佈:2020-08-16
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <vector> using namespace std; int main() { int pid = 0; int subProcessNum; std::vector<pid_t> pidList; for (subProcessNum = 0; subProcessNum < 3; subProcessNum++) { pid = fork(); if (pid == 0 || pid == -1) { break; } else { pidList.push_back(pid); } } int wait_pid = 0; if (pid == -1) { return -1; } else if (pid == 0) { printf("sub process cnt:%d\n", subProcessNum); sleep(1); exit(subProcessNum); } else { int status = 0; for (auto &pid : pidList) { if ((waitpid(pid, &status, 0) == -1) || WEXITSTATUS(status) != 0) { wait_pid = WEXITSTATUS(status); } printf("process pid:%d, exit status:%d\n", pid, WEXITSTATUS(status)); } printf("mian process exit status:%d\n", wait_pid); return wait_pid; } }