简体   繁体   English

signal()调用未触发

[英]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. 这段代码在没有时间限制的情况下可以正常运行,并且可以执行execve而没有任何问题,但是当我放入4行代码的顶行并尝试为我的execve调用cat ,孩子只是被杀死了,据推测是通过调用警报来实现的。

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. 在这种情况下, signal调用似乎根本没有做任何事情,我在killproc放置了很多痕迹,并且没有被调用。 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);

printf is not safe in a signal handler; printf在信号处理程序中并不安全; if the signal is delivered at the wrong time, internal structures will be invalid and printf will follow a bad pointer and crash. 如果在错误的时间传递了信号,则内部结构将无效,并且printf将遵循错误的指针并崩溃。 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. 可能会卡在stdio缓冲区中。

Additionally, signal() is obsolete; 此外, signal()已作废; you want to use sigaction() . 您想使用sigaction() (The manpage for sigaction should also state which interfaces are safe to use in a signal handler.) (用于sigaction的手册页还应说明可以在信号处理程序中安全使用的接口。)

Those said, neither is the real problem; 那些人说,这不是真正的问题。 the problem is you're setting a signal handler and expecting it to survive across an exec() . 问题是您正在设置信号处理程序,并期望它可以在exec()生存。 But exec() replaces the process's address space, including your signal handler ; 但是exec()替换了进程的地址空间, 包括您的信号处理程序 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; SIG_DFL可能就是您想要的(实际上是您要获得的),如果您不想修改程序,则可以exec() if you need something more, as it appears you believe you do, you will need to modify the program being exec() ed. 如果您还需要其他功能,那么您似乎需要相信,您将需要修改正在exec()的程序。

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() . 但是,我怀疑您确实还需要其他东西:无论您认为要放置在信号处理程序中的任何工具,在子级退出并通过waitpid()收获后,都确实希望在父进程中拥有该工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM