【发布时间】:2012-11-16 08:09:39
【问题描述】:
对于一个任务,我们需要实现一个带有重定向和管道的基本 shell。我的管道代码退出程序并且不再要求用户输入。管道在函数中执行,因此基本上控制不会返回给 main。我该如何做到这一点?这是我的代码:
void execute_pipe(char **argv,char **args)
{
int pfds[2];
pid_t pid;
int status;
pipe(pfds);
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
printf("here");
if (pid==0) {
close(1);
dup(pfds[1]);
close(pfds[0]);
if(execvp(argv[0],argv)<0){
printf("**error in exec");
}
}
else {
while (wait(&status) != pid) ;
close(0);
dup(pfds[0]);
close(pfds[1]);
if(execvp(args[0],args)<0){
printf("**error in exec");
}
}
}
【问题讨论】:
-
...您有问题吗?
-
对不起,问题是如何让它回到main而不退出?
-
您无法返回“main”,因为孩子 和 父母都调用
execvp。exec系列函数用来自exec调用的代码替换进程的代码。wait调用也存在问题,因为它阻塞直到子进程退出。