我有一个“一个接一个”创建新进程的程序。是否可以更改此代码以创建一个进程“列表”——即子 1 是子 2 的父,子 2 是子 3 的父,等等?
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "err.h"
using namespace std;
int main ()
{
pid_t pid;
int i;
cout << "My process id = " << getpid() << endl;
for (i = 1; i <= 4; i++)
switch ( pid = fork() ) {
case -1:
syserr("Error in fork");
case 0:
cout << "Child process: My process id = " << getpid() << endl;
cout << "Child process: Value returned by fork() = " << pid << endl;
return 0;
default:
cout << "Parent process. My process id = " << getpid() << endl;
cout << "Parent process. Value returned by fork() = " << pid << endl;
if (wait(NULL) == -1)
syserr("Error in wait");
}
return 0;
}