
我在用C程序模拟shell脚本“env | grep HOME”时遇到了麻烦。 我发现注释掉第29行解决了这个问题,但是我不确定为什么! 我读了另一个问题,这是因为dup2()closures了孩子的fd,但手册页并没有表明。 任何人都可以给我一个明确的理由,并帮助我理解这种行为? 谢谢!
#include <errno.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(voID){ pID_t childpID; int fd[2]; if(pipe(fd) == -1){ /*setup a pipe*/ perror("Failed to setup pipeline"); return 1; } if((childpID = fork()) == -1){ /*fork a child*/ perror("Failed to fork a child"); return 1; } if(childpID == 0){ /*env is the child*/ if(dup2(fd[1],STDOUT_fileNO)==-1) perror("Failed to redirect stdout of env"); else if(close(fd[0] == -1)) /*close unused file descriptor*/ perror("Failed to close extra pipe descriptors on env"); else{ execl("/usr/bin/env","env",NulL); /*execute env*/ perror("Failed to exec env"); } return 1; } if(dup2(fd[0],STDIN_fileNO)==-1) /*grep is the parent*/ perror("Failed to redirect stdin of grep"); //else if(close(fd[1]==-1)) //perror("Failed to close extra pipe file descriptors on grep"); else{ execl("/bin/grep","grep","HOME",NulL); /*execute "grep HOME"*/ perror("Failed to exec grep"); } return 1; }
F11和F12的windows扫描码是不同的。 为什么?
在dll之间使用stl遇到问题
如何在Window中保留自定义文本(Win32)
启动runas作为subprocess,并写入密码到标准input?
当添加包含netfilter.hi得到错误的字段'in','in6'具有不完整的types
我发现你的错误。 这是什么适合我的退出。 这是一个常见的错误:
... else if (close(fd[0]) == -1) /*close unused file descriptor*/ ... else if(close(fd[1]) == -1) ...
你最初做的是将文件描述符设置为关闭到布尔值fd[x] == -1 ,你想要做的是在close()的返回值中检查-1 。
总结以上是内存溢出为你收集整理的Linux / C:将pipe道redirect到STDIN / STDOUT全部内容,希望文章能够帮你解决Linux / C:将pipe道redirect到STDIN / STDOUT所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)