#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
", 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
", pid, WEXITSTATUS(status));
}
printf("mian process exit status:%d
", wait_pid);
return wait_pid;
}
}