题目
利用 fork() 创建 10 个子进程,每个子进程打印自己的 PID,父进程阻塞式地等待每个子进程结束并回收,然后打印该子进程的 PID。
源代码
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
const size_t CHILDREN_COUNT = 10;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
pid_t child[CHILDREN_COUNT];
for (size_t i = 0; i < CHILDREN_COUNT; ++i) {
child[i] = fork();
if (child[i] == 0) {
cout << "The PID of this child process is " << getpid() << endl;
return 0;
}
else if (child[i] < 0) cout << "Fork error." << endl;
}
pid_t terminated_child;
for (size_t i = 0; i < CHILDREN_COUNT; ++i) {
terminated_child = wait(nullptr);
cout << "Terminated child: " << terminated_child << endl;
}
return 0;
}