创建一个包含n个子进程的链

问题描述:

在C++中创建n个进程的链,其中n为输入,进程的输出应该为parent1-> child1(parent2) - > child2(parent3),通过使用递归函数生成输出,但无法退出循环我还需要帮助发送循环应该打破的n的输入。下面创建一个包含n个子进程的链

是我的代码:

#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 

int foo(const char *whoami) { 
    printf("I am a %s. My pid is:%d my ppid is %d\n", whoami, getpid(), getppid()); 
    return 1; 
} 

int func() { 
    pid_t pid=fork(); 
    if (pid==0) { /* only execute this if child */ 
     foo("child"); 
     pid_t pid=fork(); 
     if (pid==0) { /* only execute this if child */ 
      foo("child"); 
      func(); 
      exit(0); 
     } 
     } 
     exit(0); 
    } 
    wait(0); /* only the parent waits */ 
    return 0;  
} 

int main(void){ 
    foo("parent"); 
    func(); 
    return 0; 
} 
+0

也请删除Java标签,然后选择C或C++代码。 – stijn

你不能退出循环,原因很简单,那就是,你产生了子进程层出不穷,无论何时你开始一个新进程,然后再分叉。

#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 

int n=5; 

int foo(const char *whoami) { 
    printf("I am a %s. My pid is:%d my ppid is %d\n", whoami, getpid(), getppid()); 
    return 1; 
} 

int func(int n) 
{ 
    if (n == 0) 
    { 
     return 0; 
    } 
    int pid = fork(); 
    if (pid == -1) { 
     exit(0); 
    } 
    if (pid==0) { 
     foo("child"); 
     n = n-1; 
     func(n); 
     exit(0); 
    } 
    else { 
     wait(NULL); 
    } 
    return 0; 
} 


int main() 
{ 
    func(n); 
    return 0; 
} 

gcc -std=c99 prog.c -o prog

./prog

OUTPUT:

I am a child. My pid is: 1159 my ppid is 1158 
I am a child. My pid is: 1160 my ppid is 1159 
I am a child. My pid is: 1161 my ppid is 1160 
I am a child. My pid is: 1162 my ppid is 1161 
I am a child. My pid is: 1163 my ppid is 1162 
+0

这就是我期待的感谢! – Raj

从你说的话我理解您有以下问题:

1日。您正尝试将“数据”从一个进程发送到另一个进程

2nd。您正试图找到一种方法来阻止您的程序运行。

现在是第一个。如果你想这样做,并且我理解正确,有两种方法可以实现这一点。一个是使用共享内存,另一个是使用管道。共享内存对于正在做的事情非常明显。管道正在处理一个进程的stdout,并在下一个进程中将其重定向为stdin

现在你需要关闭你的程序。执行子进程时执行命令(exec)或者当它被告知(例如使用IF语句和返回)。你可以创建一个你喜欢的语句,当一个子进程满足你的需求时,那么你可以让它死掉(还有一种方法可以通过kill(pid, SIGKILL);命令从子进程中终止父进程

我没有' t提供任何代码,因为它不清楚我的问题的确切性质 希望我的推测能带给你什么!

+0

您的解释帮助我清除了一些关于流程感谢的疑问。 – Raj