[plug] Killing process after time

Leon Brooks leon at brooks.fdns.net
Mon May 31 01:17:49 WST 2004


On Sat, 29 May 2004 15:42, Tim White wrote:
> needs to run a process that is killed after a
> certain amount of time

This works. Note that the usleep is _needed_ else the child runs first 
and usually completes before the parent gets to set up the signal 
vector. I would do usleep(0) but it's not portable because some systems 
return immediately on a sleep value of 0.

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ctype.h>
#include <signal.h>

void die (int ignored) {
        kill (getpid(), SIGINT);
        exit (0);
}

int main (int argc, char * * argv) {
        int timeout, mypid;

        if (argc < 3 || ! isdigit (*argv[1])) {
                fprintf (stderr, "Useage: %s seconds command\n", *argv);
                exit (1);
        }
        timeout = atol (argv[1]);
        mypid = fork ();
        if (mypid) {
                signal (SIGCHLD, die);
                sleep (timeout);
                signal (SIGCHLD, SIG_DFL);
                kill (mypid, SIGKILL);
        } else {
                usleep(1); /* give up CPU to parent */
                execvp (argv [2], argv + 2);
        }
        exit (1);
}

Cheers; Leon



More information about the plug mailing list