我有一个程序可以“逐个”创建新进程。是否可以更改此代码,以便创建进程的“列表” - 即子项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;
}
答案 0 :(得分:3)
在一组嵌套fork
if
#include<stdio.h>
int main()
{
printf("Parent PID %d\n",getpid());
if(fork()==0)
{
printf("child 1 \n");
if(fork()==0)
{
printf("child 2 \n");
if(fork()==0)
printf("child 3 \n");
}
}
return 0;
}
输出
父PID 3857
孩子1
孩子2
孩子3
对于n个进程,
#include<stdio.h>
void spawn(int n)
{
if(n)
{
if(fork()==0)
{
if(n)
{
printf("Child %d \n",n);
spawn(n-1);
}
else
return;
}
}
}
int main()
{
printf("Parent PID %d\n",getpid());
int i=0;
spawn(5);
return 0;
}
答案 1 :(得分:3)
如果你想保持循环以便动态设置 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
答案 2 :(得分:-2)
int make_proc(int counter, int parent){
pid_t x=getpid();
std::cout << counter << " process "<< x << " : parent" << parent<< std::endl;
if (counter==0) {
return 1;
}
else {
counter=counter-1;
pid_t pid=fork();
if (pid==0) return make_proc(counter, x);
wait(NULL);
}
}
--------------------
int main(int argc, char **argv)
{
int x=getpid();
make_proc(10, x);
return 0;
}