3

I need your help !

I made a reporting deamon (in c++) which needs to periodicaly execute a bunch of commands on a server.

A simple example command would be : "/bin/ps aux | /usr/bin/wc -l"

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.

I tried using "sleep 20000" as command, the child process is killed but the sleep command is still running... not good.

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.

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" :

execlp("sh","sh","-c","/bin/ps aux | /usr/bin/wc -l",NULL);

I works... or so I thought... I tried

execlp("sh","sh","-c","sleep 20000",NULL); 

just to be sure and the child process is killed after 5 secs (my timeout) but the sleep command just stays there...

i'm open for suggestions (I'd settle for a hack) !

Thanks in advance !

TLDR;

I need a way to :

  • execute a "complex" command such as "/bin/ps aux | /usr/bin/wc -l"
  • get its output
  • make sure it's killed if it takes more than 5 seconds (the ps command is just and example, actual commands may hang forever)
srsbsns
  • 300
  • 4
  • 10

1 Answers1

7

Use timeout command from coreutils:

/usr/bin/timeout 5 /bin/sh -c "/bin/ps aux | /usr/bin/wc -l"
Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • Thanks ! I can't test at the moment but I'll try when I get home ! One thing though, killing the child process with my solution killed the "sh -c" as well, but somehow the "sleep 20000" process managed to stay. – srsbsns Jan 07 '13 at 12:09
  • 1
    Before recommending `timeout`, I tested it and ensured that `sleep` is terminated too. – Anton Kovalenko Jan 07 '13 at 13:25
  • 1
    `execlp("timeout","timeout","5","sh","-c","ls -lisa | grep etc",NULL);` It works, thanks ! – srsbsns Jan 07 '13 at 19:44