Search code examples
cexecprocesspopenps

popen creates an extra sh process


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?


Solution

  • 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", ...