在下文中,子进程创建对象。它使用信号在一段时间后自杀:
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Wut{
public:
Wut(){cout<<"obj being created" << endl;}
~Wut(){cout<<"obj being destroyeed" << endl;}
};
void alarmHandler(){
cout << "Alarm! Forcing child to kill itself" << endl;
kill(getpid(), SIGKILL);
}
int main(int argc, char* argv[]){
int status;
pid_t pid;
if((pid = fork()) == 0){
Wut hi;
signal(SIGALRM, (sighandler_t)alarmHandler);
alarm(1);
alarm(7);
sleep(10);
cout << "this will not get printed" << endl;
} else {
wait(&status);
cout << "Parent dies" << endl;
}
sleep(10);
return 0;
}
但我不确定它创建的对象是否被正确销毁,因为它从不调用析构函数。
答案 0 :(得分:3)
KILL信号实际上没有发送到进程;这是操作系统强制停止程序执行的信号。这意味着不会调用析构函数。
使用SIGTERM
之类的信号来查看预期的行为:
kill(getpid(), SIGTERM);
答案 1 :(得分:2)
Unix进程无法以任何方式处理SIGKILL
。你的过程立刻就像一个门钉一样死了。如果您想要优雅退出,请查看SIGTERM
。然后,您可以注册一个处理程序来执行您需要的任何清理工作。
您可以使用处理程序将程序置于正常退出的状态(例如,通过设置标志等),允许析构函数运行。
答案 2 :(得分:0)
SIGKILL
(在大多数情况下)与kill -9
相同,因此操作系统会回收分配给该进程的所有内存。