【发布时间】:2019-04-19 18:35:45
【问题描述】:
你能给我一些关于以下代码的想法吗?代码运行但不退出。另一个字符串s="ls -1" 运行良好。通过sh(1) 运行shell sn-p 也可以正常工作。
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int fd[2];
char *s = "ls -1 \"/usr/bin\" | while IFS= read -r fp\ndo\ncat <<- EOF\n\t$fp\nEOF\ndone;";
//char *s = "ls -1";
pipe(fd);
switch(fork()) {
case 0:
close(fd[1]);
dup2(fd[0], 0);
execl("/bin/sh", "sh", NULL);
close(fd[0]);
break;
default:
close(fd[0]);
write(fd[1], s, strlen(s) + 1);
close(fd[1]);
break;
}
return 0;
}
【问题讨论】:
-
在这种情况下,
close(fd[0]);需要在execl()之前——记住,如果成功,execl()永远不会返回(它只会在失败时返回)。你应该有一个错误报告和exit(1);或execl()之后的类似内容;目前,即使失败了,你也会报告成功。 -
@JonathanLeffler,我想知道
execl和close(fd[0]);的顺序,你的cmets 是有道理的,但是,切换它们的顺序仍然不起作用。它的行为方式相同,不会退出。 -
查看我的回答——是的,我同意 cmets 不是您问题的解决方案,尽管 exec 之后的关闭没有执行,并且那里应该有一条错误消息。
-
也可能与大量的 heredocs 和 tmp 文件有关。