【发布时间】:2020-06-12 20:57:29
【问题描述】:
我正在编写一个函数,它将输入回显到一个 sed,然后是另一个 sed。我认为我以正确的方式使用了所有等待信号,但我能得到的最后一个打印是在 echo 中我的第一个子进程中对 dup2() 的调用之前。
void sendbc (char * str_ ) {
int fd[2];
int fd1[2];
int pid,pid1;
char* echo[] = {"echo", str_,NULL};
char* sed1[] = {"sed","s/[^:]*;"" " "//",NULL};
char* sed2[] = {"sed","s/[^:]*."" " "//",NULL};
int status,er;
FILE *f;
if(pipe(fd) < 0){
exit(100);
}
if(pipe(fd1) < 0){
exit(100);
}
pid = fork();
if (pid == 0) {
dup2(fd[1], 1) //last command before blocking
close(fd[1]);
close(fd[0]);
execvp(echo[0], echo);
printf("Error in execvp1\n");
}else{
wait(&status);
pid = fork();
if (pid == 0){
dup2(fd[0], 0);
dup2(fd1[1], 1);
dup2(fd1[1], 2);
close(fd[1]);
close(fd[0]);
close(fd1[1]);
close(fd1[0]);
execvp(sed1[0],sed1);
printf("Error in execvp2\n");
}else{
wait(&status);
dup2(fd1[0],0);
dup2(1,2);
//dup2(1,1);
close(fd1[1]);
close(fd1[0]);
execvp(sed2[0],sed2);
printf("Error in execvp3\n");
}
}
if(pid!=0)
wait(&status);
close(fd[0]);
close(fd[1]);
close(fd1[1]);
close(fd1[0]);
}
我可以想象 2 种可能性... dup2 正在阻塞或我需要创建更多进程,因为它结束了待命进程,但是在快速阅读他的手册页后这听起来不太正确... 它可能是什么?
【问题讨论】:
-
我无法回答你的问题,但你确定这个字符串是它应该是什么?:
"s/[^:]*;"" " "//" -
不,它是随机类型,但这意味着在 ';' 之前全部剪切以及'.'之前的所有内容。无论如何,我打印了进程的跟踪,所有这些都在 echo dup2 中被阻止...
-
您通常应该同时运行管道中的进程,而不是运行一个,等待它完成,然后运行下一个。您的数据量可能足够小,没有问题;有大量数据,可能会导致死锁。此外,错误消息应打印到
stderr,而不是stdout。 -
请注意
.是sed的元字符。如果要搜索点,请使用[.]或反斜杠转义(但要多少个反斜杠 - 您需要两个"\\."以便编译器生成字符串反斜杠点。如果您使用system()而不是fork()和execvp(),您需要在 C 代码中使用 4 个反斜杠。