Time limit exceeded (or how to kill my children)

I want to put a limit in the time a process could run.
First try
1
2
3
4
5
#include <unistd.h>
//...
    alarm(limit);
    if(execv(program, args) == -1)
        perror("Error at execv");

The problem comes because I want to perform some actions before terminating
man wrote:
During an execve(2), the dispositions of handled signals are reset to the default; the dispositions of ignored signals are left unchanged.


Second try
1
2
3
4
5
6
7
8
9
10
11
12
13
void time_limit_exceeded(int);
    int pid = fork();
    if( pid ){//parent
        struct sigaction handler;
        handler.sa_handler = time_limit_exceeded;
        sigaction(SIGALRM, &handler, NULL);
        alarm(limit);
        waitpid(pid, NULL, 0); //avoid zombie (and orphan)
    }
    else{ //child
        if(execv(argv[2], argv+2)==-1)
            perror("Error at execv");
    }
The problem is that the only parameter that the handler receives is the signal that activated it. How could I know the pid of the child I need to kill (without a global)
kill(0, SIGKILL); will kill the parent too (I don't think I want that)

Another thing: how can I set up an environment to the child, so it cannot perform some system calls (like fork) ?
Last edited on
If you are doing this on Linux, I can answer your last question: use LSM/SELinux.

http://selinuxproject.org/page/NB_LSM
Topic archived. No new replies allowed.