【发布时间】:2016-01-05 16:44:57
【问题描述】:
我想创建与用户在参数中发送的一样多的子进程。我成功了。但是,我必须使用exec 函数创建子进程,我不知道该怎么做。 Childs 进程将被创建为单独的程序并运行
通过执行。此外,我希望每个子进程都使用pipe 与主进程(父进程)进行通信。我不知道怎么做。到目前为止,我设法写了这样的东西:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
pid_t pid;
if(argc < 3)
{
printf("Not enought arguments");
exit(0);
}
int number = atoi(argv[2]); // number of childern
pid_t pids[number],pid_s;
int i,n=number,status;
int pipes[number*2];
char buff[512];
if(strcmp("-p", argv[1]) == 0)
{
//
}
if(strcmp("-f", argv[1]) == 0)
{
//
}
switch (pid = fork()) {
case -1:
perror("Error in fork");
exit(0);
break;
case 0:
for(i=0; i < n; i++)
{
if((pids[i] = fork()) < 0)
{
perror("error fork");
}
else if(pids[i] == 0)
{
close(pipes[0]);
char *reply = "message";
write(pipes[1], reply, strlen(reply)+1);
execvp(argv[0],NULL);
}
}
while(n > 0)
{
pid_s = wait(&status);
--n;
}
break;
default:
close(pipes[1]);
read(pipes[0],buff,80);
printf("Message: %s", buff);
if(wait(0) == -1)
{
}
break;
}
return 0;
}
我更正了代码,子进程由 exec 创建了一个新进程。我想通过管道将子进程与主进程通信。最好循环执行吗?
【问题讨论】:
-
execve()系列函数不创建子进程。对于像您这样的问题,您可以在分叉后使用其中一个 exec 函数,将分叉的子镜像替换为任意替代程序镜像。也就是说, exec 是您指导进程运行不同程序的方式。 -
对于管道,子进程继承其父进程的所有文件描述符。您可以通过
pipe()函数创建一对表示管道末端的已连接、打开的文件描述符。如果你在分叉之前这样做,那么父母可以写到写端,孩子可以从读端读(反之亦然)。 -
@JohnBollinger 分叉后我到底可以使用什么 exec ?
-
exec 替换现有的子进程,而不是创建/运行子进程。 stackoverflow.com 上有很多关于如何使用 exec() 系列函数的示例。建议进行一些搜索。
-
以
for(i=0; i < n; i++)开头的代码块应该在switch()语句之前并包含switch语句。但是,对 execvp() 的调用应保留在子执行路径中。注意:由于 argv[] 来自 main() 函数签名,因此此代码将永远继续重新执行自身。建议通过调用execvp()运行不同的程序