theeggman85
theeggman85

Reputation: 1825

signal() call not firing

I am attempting to write some code that forks a new process, but kills that new process after some amount of time if it is taking too long. This code works fine without the time restraint and executes execve without any problem, but when I put the 4 top lines of code in and try to call cat for my execve, the child simply is killed, assumedly by the call to alarm.

The signal call doesn't seem to be doing anything at all in this case, I have put numerous traces in killproc and it is not being called. How am I setting up this timing system incorrectly?

void killproc(int sig) {
    printf("running?");
}

Code: (in child)

if(MAX_TIME != -1){
    signal(SIGALRM, killproc);
    alarm(MAX_TIME);
}
// Process we are timing
int ret = execve(path, newargv, envp);

Upvotes: 0

Views: 129

Answers (1)

geekosaur
geekosaur

Reputation: 61379

printf is not safe in a signal handler; if the signal is delivered at the wrong time, internal structures will be invalid and printf will follow a bad pointer and crash. Have you tested this with some other operation? Even if it doesn't crash, you aren't flushing output or printing a newline, so the "running?" will probably be stuck in a stdio buffer.

Additionally, signal() is obsolete; you want to use sigaction(). (The manpage for sigaction should also state which interfaces are safe to use in a signal handler.)

Those said, neither is the real problem; the problem is you're setting a signal handler and expecting it to survive across an exec(). But exec() replaces the process's address space, including your signal handler; accordingly, it resets the handler, since it knows that no function pointer for a signal handler will be valid afterward. SIG_DFL is probably what you want here (and in fact what you're getting), if you don't want to modify the program you're exec()ing; if you need something more, as it appears you believe you do, you will need to modify the program being exec()ed.

I suspect, however, that you really want something else: whatever instrumentation you think you want to put in the signal handler, you really want to have in the parent process after the child exits and is reaped with waitpid().

Upvotes: 3

Related Questions