Note that there are some explanatory texts on larger screens.

plurals
  1. POExecuting commands with pipes and timeout in c++ (and reading stdout)
    text
    copied!<p>I need your help !</p> <p>I made a reporting deamon (in c++) which needs to periodicaly execute a bunch of commands on a server.</p> <p>A simple example command would be : "/bin/ps aux | /usr/bin/wc -l"</p> <p>The first idea was to fork a child process that runs the command with popen() and set up an alarm() in the parent process to kill the child after 5 seconds if the command has not exited already.</p> <p>I tried using "sleep 20000" as command, the child process is killed but the sleep command is still running... not good.</p> <p>The second idea was to use execlp() instead of popen(), it works with simple commands (ie with no pipes) such as "ls -lisa" or "sleep 20000". I can get the result and the processes are killed if they're not done after 5 seconds.</p> <p>Now I need to execute that "/bin/ps aux | /usr/bin/wc -l" command, obviously it won't work with execlp() directly, so I tried that "hack" : </p> <pre><code>execlp("sh","sh","-c","/bin/ps aux | /usr/bin/wc -l",NULL); </code></pre> <p>I works... or so I thought... I tried </p> <pre><code>execlp("sh","sh","-c","sleep 20000",NULL); </code></pre> <p>just to be sure and the child process is killed after 5 secs (my timeout) but the sleep command just stays there...</p> <p>i'm open for suggestions (I'd settle for a hack) !</p> <p>Thanks in advance !</p> <p>TLDR; </p> <p>I need a way to :</p> <ul> <li>execute a "complex" command such as "/bin/ps aux | /usr/bin/wc -l" </li> <li>get its output</li> <li>make sure it's killed if it takes more than 5 seconds (the ps command is just and example, actual commands may hang forever)</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload