我想创建与用户在参数中发送的子进程一样多的子进程。我成功了。但是,我必须使用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创建了一个新进程。我希望孩子通过管道与主要流程沟通。最好是循环吗?
答案 0 :(得分:1)
这个示例代码,剪切自:http://www.cs.ecu.edu/karl/4630/sum01/example1.html显示了如何使用execvp()
函数,我做了一些修改。
它使用函数parsecmd(cmd,argv),这里没有写入,但它在空格处打破cmd并将这些块存储到(本地数组)argv []中,后跟一个空指针。例如,parsecmd(“吃香蕉”,argv)将设置argv如下。
argv[0] = "eat"
argv[1] = "the"
argv[2] = "banana"
argv[3] = NULL
This example also presumes that there might be other child processes running in background, and that they might terminate while the shell is waiting for the current command to stop. A function called process_terminated is use to handle the termination of a background process. It is not written here.
int runcmd(char *cmd)
{
char* argv[MAX_ARGS];
pid_t child_pid;
int child_status;
parsecmd(cmd,argv);
child_pid = fork();
if(child_pid == 0) {
/* This is done by the child process. */
execvp(argv[0], argv);
/* If execvp returns, it must have failed. */
fprintf( stderr, "execvp failed due to %s\n", strerror(errno) );
exit(0);
}
else {
/* This is run by the parent. Wait for the child
to terminate. */
do {
pid_t tpid = wait(&child_status);
if(tpid != child_pid) process_terminated(tpid);
} while(tpid != child_pid);
return child_status;
}
}