popen/pclose 的替代品?
我正在编写一个必须执行其他外部进程的程序; 现在,程序通过 popen 启动进程的命令行,获取任何输出,然后通过 pclose 获取退出状态。
然而,发生的情况是,对于快速运行的进程(例如,启动的进程很快就会出错),pclose 调用无法获取退出状态(pclose 返回 -1,errno 为 ECHILD)。
有没有办法让我模仿 popen/pclose 类型的行为,除了保证捕获进程结束“事件”和结果返回代码的方式? 如何避免 pclose 固有的竞争条件和启动进程的终止?
I'm writing a program that has to execute other external processes; right now the program launches the processes' commandlines via popen, grabs any output, and then grabs the exit status via pclose.
What is happening, however, is that for fast-running processes (e.g. the launched process errors out quickly) the pclose call cannot get the exit status (pclose returns -1, errno is ECHILD).
Is there a way for me to mimic the popen/pclose type behavior, except in a manner that guarantees capturing the process end "event" and the resultant return code? How do I avoid the inherent race condition with pclose and the termination of the launched process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fork/exec/wait
popen 只是一个简化 fork/exec 调用的包装器。 如果要获取子进程的输出,则需要创建一个管道,调用 fork,将子进程的文件描述符复制到管道,然后执行。 父级可以读取管道的输出并调用 wait 来获取子级的退出状态。
fork/exec/wait
popen is just a wrapper to simplify the fork/exec calls. If you want to acquire the output of the child, you'll need to create a pipe, call fork, dup the child's file descriptors to the pipe, and then exec. The parent can read the output from the pipe and call wait to get the child's exit status.
您可以使用 vfork() 和 execv()。
You can use vfork() and execv().