popen creates an extra sh process

我的梦境 提交于 2019-12-10 10:45:40

问题


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?


回答1:


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 - add exec to the beginning of the command line you pass to popen. That is, instead of:

popen("my_command /home/war", ...

use:

popen("exec my_command /home/war", ...



回答2:


popen uses sh to spawn the child process, like system does on POSIX systems.

If you want to avoid it, just use fork, close, mkpipe and exec (which is more or less what popen does internally). If you don't need the pipe you can just fork and exec.




回答3:


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



来源:https://stackoverflow.com/questions/6742635/popen-creates-an-extra-sh-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!