【发布时间】:2012-11-16 18:41:42
【问题描述】:
我正在用 C 实现一个 shell。这是我用于管道的函数。当我在代码中输入“ls | a”(即用无效命令传递有效命令)时,它不会像应有的那样退出子进程。我如何让它回到主要功能? 当我做 ps | 时也会发生同样的事情ls或ps | pwd 等,但 ls | ps 的工作方式与 bash 相同。我知道ls | ps或ps | ls 没有意义,但至少它们应该提供与 bash 相同的输出。
void exec3(char **args, char **args2){
int fd[2];
pid_t pid,pid1;
int status;
pipe(fd);
int e=0;
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if ((pid1 = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0 && pid1!=0){
printf("in 1\n");
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
if(execvp(args[0],args)<0){
printf("**error in exec");
close(fd[0]);
close(fd[1]);
exit(1);
}
//printf("exiting 1\n");
exit(0);
}
else if (pid1 == 0 && pid!=0) {
printf("in 2\n");
close(0);
dup(fd[0]);
close(fd[1]);
close(fd[0]);
if((e=execvp(args2[0],args2))<0){
printf("**error in exec2 ");
close(fd[0]);
close(fd[1]);
exit(1);
}
exit(0);
}
else {
close(fd[0]);
close(fd[1]);
fflush(stdout) ;
while (wait(&status) != pid);
while (wait(&status) != pid1);
}
}
【问题讨论】:
-
阅读advancedlinuxprogramming.com之类的好书,研究
sash之类的一些小型免费软件shell的源代码。 -
快速提问:你是 Epitech 的吗? :)
-
错误信息属于标准错误。
printf( "ERROR...总是是错误的。perror是你的朋友。