2
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>

int main(){

    pid_t pid = fork();

    if(pid==0){
            system("watch ls");
    }
    else{
            sleep(5);
            killpg(getpid(),SIGTERM);  //to kill the complete process tree.
    }
    return 0;
}

终端:

anirudh@anirudh-Aspire-5920:~/Desktop/testing$ gcc test.c
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ ./a.out
Terminated

前 5 秒显示“watch ls”的输出,然后它终止,因为我发送了一个 SIGTERM。

问题:进程如何杀死自己?我已经完成了 kill(getpid(),SIGTERM);

我的假设: 所以在 kill() 调用过程中,进程切换到内核模式。kill 调用将 SIGTERM 发送到进程并将其复制到进程的进程表中。当进程返回到用户模式时,它会在其表中看到信号并自行终止(如何?我真的不知道) (我认为我的假设某处出错了(可能是一个错误)......所以请开导我)

这段代码实际上是一个存根,我用它来测试我的项目的其他模块。它为我完成了这项工作,我对此感到满意,但我心中存在一个问题,一个过程实际上是如何杀死自己的。我想知道一步一步的假设。

提前致谢

阿尼鲁德·托默

4

5 回答 5

3

您的进程死亡是因为您正在使用killpg(),它向进程组发送信号,而不是向进程发送信号。

当 youfork()时,孩子们从父亲那里继承,除此之外,还有进程组。来自man fork

   *  The child's parent process ID is the same as the parent's process ID.

所以你把父母和孩子一起杀了。

如果你做一个简单kill(getpid(), SIGTERM)的然后父亲会杀了孩子(即watching ls)然后会和平退出。

于 2011-02-15T18:05:17.417 回答
2

so during the kill() call the process switches to kernel mode. The kill call sends the SIGTERM to the process and copies it in the process's process table. when the process comes back to user mode it sees the signal in its table and it terminates itself (HOW ? I REALLY DO NOT KNOW )

In Linux, when returning from the kernel mode to the user-space mode the kernel checks if there are any pending signals that can be delivered. If there are some it delivers the signals just before returning to the user-space mode. It can also deliver signals at other times, for example, if a process was blocked on select() and then killed, or when a thread accesses an unmapped memory location.

于 2011-02-15T18:22:52.873 回答
0

我认为当它在其进程表中看到 SIGTERM 信号时,它首先杀死其子进程(完整树,因为我调用了 killpg() )然后它调用 exit()。

我仍在寻找这个问题的更好答案。

于 2011-01-09T04:35:40.660 回答
0
kill(getpid(), SIGKILL);  // itself I think

我在forkwith case 0: 之后对其进行了测试,它从单独的父进程中定期退出。

不知道这算不算标准的认证方式....

(我可以从我的 psensor 工具中看到 CPU 使用率返回 34%,就像计数器停止的正常程序代码一样)。

于 2014-08-29T16:34:56.323 回答
-4

这在 Perl 中非常简单:

   { 
        local $SIG{TERM} = "IGNORE";
        kill TERM => -$$;
   }

转换为 C 留给读者作为练习。

于 2011-02-15T18:24:50.867 回答