popen 创建一个额外的 sh 进程
我正在尝试使用 popen 执行(分叉)命令,我看到的是,还有一个额外的 sh -c "my_command process"
也在那里。
我想最大程度地减少进程数量,那么可以摆脱它吗?
ps 输出:
root@home% ps awux | grep my_command
root 638 0.0 0.1 040 1424 ?? I 10:12PM 0:00.00 sh -c my_command /home/war
root 639 0.0 0.0 608 932 ?? S 10:12PM 0:00.01 my_command /home/war
阅读手册页后,我知道这就是 popen() 的工作原理。
上述问题的答案是由 @R 提供的。
我的要求是这样的,我需要将命令的输出转储到文件中并逐行读取该文件并处理输出。这就是我使用 popen 的原因,因为它返回文件中的输出。我可以通过任何 exec 调用来实现这一点吗?
I am trying to execute (fork off) a command with popen and what I see is, there is an extra sh -c "my_command process"
is also there.
I want to minimize number of processes so is it possible to get rid of it?
ps output:
root@home% ps awux | grep my_command
root 638 0.0 0.1 040 1424 ?? I 10:12PM 0:00.00 sh -c my_command /home/war
root 639 0.0 0.0 608 932 ?? S 10:12PM 0:00.01 my_command /home/war
After reading manpage, I know this is how popen() works.
Answer to problem above was provided by @R..
My requirement is as such, I need to dump output of the command into a file and read that file line by line and process the output. This is why I am using popen because, it returns output in a file. Can I achieve that via any exec call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该听取那些建议您不要使用
popen
的好心人的意见 - 这很糟糕。但是,对于您遇到的问题,有一个简单的解决方案 - 将exec
添加到传递给popen
的命令行的开头。也就是说,代替:使用:
You should listen to the good folks who are advising you not to use
popen
- it's bad. But there is a simple fix for the issue you've encountered - addexec
to the beginning of the command line you pass topopen
. That is, instead of:use:
popen
使用sh
生成子进程,就像system
在 POSIX 系统上所做的那样。如果你想避免它,只需使用
fork
、close
、mkpipe
和exec
(这或多或少popen
内部做了什么)。如果您不需要管道,您只需fork
和exec
即可。popen
usessh
to spawn the child process, likesystem
does on POSIX systems.If you want to avoid it, just use
fork
,close
,mkpipe
andexec
(which is more or less whatpopen
does internally). If you don't need the pipe you can justfork
andexec
.就popen而言,它应该调用shell(阅读手册页)
要跳过shell进程,您可以执行fork/exec
As far as popen is concerned, it is supposed to invoke the shell (read the manpage)
To skip the shell process, you can do a fork/exec