c++ - 对象是否会通过kill正确地被销毁?

标签 c++ linux unix object

接下来,子进程创建该对象。它使用信号在一段时间后杀死自己:

#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;
}

但我不确定它创建的对象是否被正确销毁,因为它从不调用析构函数。

最佳答案

KILL信号实际上并没有发送到进程;它是操作系统强行停止程序执行的信号。这意味着析构函数不会被调用。

使用像 SIGTERM 这样的信号来查看预期的行为:

kill(getpid(), SIGTERM);

关于c++ - 对象是否会通过kill正确地被销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10341430/

相关文章:

通过忽略不必要的行来区分 linux

Linux tc(流量控制)工具 - 配置后 ssh 连接问题

unix - UNIX 中的/dev/tty 是什么?

bash - 如何使用 Bash 脚本中的密码运行 sftp 命令?

c++ - 如何从 .NET 代码中使用 Activator 调用的 COM 库打印到控制台?

c++ - SDL 链接器错误

linux - 我可以在 tar 文件仍在创建时对其进行 rsync 吗?

c++ - C++ 风格转换对性能的影响?

c++ - 如何去除图像中的小平行线?

linux - 如何从 shell 脚本返回特定变量的值?