通过 PID 分配信号处理程序

assign signal handler by pid

本文关键字:程序 信号处理 分配 PID 通过      更新时间:2023-10-16

如果我知道某个进程的pid不运行代码(比如火狐) 如何为其分配信号处理程序(例如 SIGINT)?

我现在有 :

pid = fork();
printf("forked and my pid is %dn",pid);
//check for errors
if (pid<0){         
printf("Error: invoking fork to start ss has failed, Exitingn ");
exit(1);
}
//the child process runs the gulp
if (pid==0){
printf("STARTING THE FIREFOXn");           
//calling signal(somehandler,SIGINT); here will bind the child, which is replaced by the firefox new process,hence won't invoke the "somehandler"
if (execv(args[0],args)<0){
perror("Error: running s with execvp has failed, Exitingn");
}
//invoking signal(somehandler,SIGINT); will obviously not do anything
printf("IVE BEEN KILLEDn");            
}
//dad is here
printf("DAD IS GOING TO KILLn");
if (pid>0){
sleep(6);
//how do I bind a handler to that signal????
kill(get_pidof(string("firefox")),SIGINT);
}

您只能在流程建立信号处理程序。换句话说,你不能让 Firefox 在获得 SIGINT 时调用你的信号处理程序。


编辑

正如您所注意到的,信号处理程序确实不会在执行之后保留 - 进程的图像被替换,因此没有意义。所以,就像我之前说的:即使你控制了它的父级,你也无法firefox调用你的处理程序。

我需要我的程序运行另一个程序(比如火狐),并且知道 当火狐死亡或崩溃时

在这种情况下,您想为SIGCHLD建立一个信号处理程序:当孩子死亡时,您的进程将跳转到它。

正如Cnucitar在这里回答的那样,您只能从进程内部更改信号处理程序。

如果你想在 Firefox 中制作一个信号处理程序,你可以修补它,也许通过一个插件。但我相信这将是一个坏主意。