我有一个程序可以“一个一个”地创建新进程。是否可以更改此代码以创建一个进程“列表”——即子 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;
}
最佳答案
如果你想保持循环以便动态设置fork树的深度,
// Set DEPTH to desired value
#define DEPTH 4
int main ()
{
pid_t pid;
int i;
cout << "My process id = " << getpid() << endl;
for (i=1 ; i <= DEPTH ; i++) {
pid = fork(); // Fork
if ( pid ) {
break; // Don't give the parent a chance to fork again
}
cout << "Child #" << getpid() << endl; // Child can keep going and fork once
}
wait(NULL); // Don't let a parent ending first end the tree below
return 0;
}
输出
My process id = 6596
Child #6597
Child #6598
Child #6599
Child #6600
关于C++ fork()——创建 "list"进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16890546/