即使我在Linux(Mint 18.3)上使用kill命令发送信号,WIFSIGNALED也会返回false

时间:2018-09-13 23:00:37

标签: c linux waitpid sigterm

问题:我需要打印进程接收到的终止信号,

对于示例

如果我发送一个 *kill -15 1245* ,其中1245是进程的pid,则我的程序应打印类似 "Process killed by signal 15" 的内容,即使我向进程 *kill -15*

发送 WIFSIGNALED macro returns false and obviously WTERMSIG returns 0.

系统::我使用的是基于Ubuntu发行版的Linux Mint 18.3,并且在其他Ubuntu发行版中测试了我的程序,但仍然无法正常工作,但在Fedora和OpenSUSE中却运行良好。有想法吗?

代码:

//Libraries
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>

//Macros
#define MAX_LIMIT 50

//Function where i create a child process and execute a shell over it.
void run(char comando[])
{
    int status;
    pid_t pid;
    if((pid = fork()) == 0)
        execlp("sh", "sh", "-c", comando, NULL);
    pid = waitpid(pid, &status, 0);
    //The problem begins here, the WIFEXITED returns *true* even is the process was killed by a signal.
    if(WIFEXITED(status))
        printf("Process ended with status %d\n", 
WEXITSTATUS(status));
    //Is here when i need to print the signal, but WIFSIGNALED returns *false* even if a signal was sended by the *kill* command.
    else if(WIFSIGNALED(status))
        printf("Process killed by signal %d\n", 
WTERMSIG(status));
    else if(WIFSTOPPED(status))
        printf("Process stopped by signal %d\n", 
WSTOPSIG(status));
    else if(WIFCONTINUED(status))
        printf("Process continued...\n");
} 
//Function that simulates a shell by repeating prompt.
void shell()
{
    run("clear");
    printf("\t\t\t\t\tMINI_SHELL\n");
    char comando[MAX_LIMIT];
    do
    {
        printf("$> ");
        fgets(comando, MAX_LIMIT, stdin);
        char *cp = strchr(comando,'\n'); if (cp != NULL) *cp =  0;
        if(strcmp(comando, "ext") != 0)
            run(comando);
    } while(strcmp(comando, "ext") != 0);
}

int main(int argc, char *argv[])
{
    shell();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

这全都归结为基于debian的发行版(/bin/dash)和基于redhat的发行版(/bin/bash)的默认外壳之间的区别。

通话时

execlp("sh", "sh", "-c", comando, NULL);

使用commando"cat"之类的"echo 1; cat",如果sh/bin/dash(如在debian上),则外壳程序将调用waitpid()退出前本身的状态为cat;如果sh/bin/bash,它将仅exec到脚本中的最后一个命令。

尝试在小型外壳程序中输入类似echo pid=$$; cat的命令,然后输入kill的echo值而不是cat的pid,您将得到预期的'Process被信号杀死...'