用SIGTERM杀死孩子

时间:2018-08-11 12:38:16

标签: c unix signals posix handler

我有2个程序: 1) 父亲 2) Child 。 当父亲收到SIGINT(CTRL-C)信号时,其处理程序将SIGTERM发送给他的孩子。问题在于,通常(并非总是如此,不知道为什么)它会在SIGINT之后循环显示此错误:

Invalid Argument

父亲的目标是生一个孩子,然后活着准备好处理SIGINT。

父亲

#include "library.h"

static void handler();

int main(int argc, char* argv[]){
    int value, que_id;
    char str_que_id[10], **child_arg;
    pid_t child_pid;
    sigaction int_sa;

    //Create message queue
    do{
        que_id = msgget(IPC_PRIVATE, ALL_PERM | IPC_CREAT);
    }while(que_id == -1);
    snprintf(str_que_id, sizeof(str_que_id), "%d", que_id);

    //Set arguments for child
    child_arg = malloc(sizeof(char*) * 3);
    child[0] = "child";
    child[1] = str_que_id;
    child[2] = NULL;

    //Set handler for SIGINT
    int_sa.sa_handler = &handler;
    int_sa.sa_flags = SA_RESTART;
    sigemptyset(&int_sa.sa_mask);
    sigaddset(&int_sa.sa_mask, SIGALRM);
    sigaction(SIGINT, &int_sa, NULL);

    //Fork new child
    if(value = fork() == 0){
        child_pid = getpid();
        do{
            errno = 0;
            execve("./child", child_arg, NULL);
        }while(errno);
    }

    //Keep alive father
    while(1);

    return 0;
}

static void handler(){
    if(kill(child_pid, SIGTERM) != -1)
        waitpid(child_pid, NULL, WNOHANG);
    while(msgctl(que_id, IPC_RMID, NULL) == -1);
    free(child_arg);
    exit(getpid());
}

孩子的目标(仅现在在我的项目中)只是为了等待从消息队列收到的新消息。由于不会有任何消息,因此它将始终被阻止。

孩子

#include "library.h"

typedef struct _Msgbuf {
    long mtype;
    char[10] message;
} Msgbuf;

int main(int argc, char * argv[]){
    int que_id;

    //Recovery of message queue id
    que_id = atoi(argv[1]);

    //Set handler for SIGTERM
    signal(SIGTERM, handler);

    //Dynamic allocation of message
    received = calloc(1, sizeof(Msgbuf));

    while(1){
        do{
            errno = 0;
            //This will block child because there won't be any message incoming
            msgrcv(que_id, received, sizeof(Msgbuf) - sizeof(long), getpid(), 0);
            if(errno)
                perror(NULL);
        }while(errno && errno != EINTR);
    }
}

static void handler(){
    free(received);
    exit(getpid());
}

我从man pages on msgrcv()知道:

  

呼叫过程捕获信号。在这种情况下,系统调用将 errno 设置为 EINTR 而失败。 (无论建立信号处理程序时 SA_RESTART 标志的设置如何, msgrcv ()都不会在被信号处理程序中断后自动重新启动。)

那么为什么要循环打印该错误?它应该在处理程序中退出,相反,似乎在处理程序返回之后(由于free(received)),它找不到将errno设置为 EINVAL 的消息的缓冲区。

2 个答案:

答案 0 :(得分:1)

(几乎)总是errno only 仅当函数调用失败时才带有合理值。

msgrcv()就是这种情况。

来自msgrcv()'s documentation

  

返回值

     

成功完成后,msgrcv()将返回一个等于实际放入缓冲区mtext的字节数的值。否则,将不会接收到任何消息,msgrcv()将返回-1,并且errno将被设置为指示错误。

因此,仅当errno返回msgrcv()时使用-1,否则errno的值是不确定的,并且很可能包含垃圾内容...

下面的代码没有意义...

        msgrcv(que_id, received, sizeof(Msgbuf) - sizeof(long), getpid(), 0);
        if(errno)
            perror(NULL);
      } while(errno && errno != EINTR);

...,应类似于:

        if (-1 == msgrcv(que_id, received, sizeof(Msgbuf) - sizeof(long), getpid(), 0))
        {
          /* Only here errno had a well defined value. */
          perror("msgrcv() failed"); /* perror() translates errno into a human readable text prefixed by its argument and logs it to the stderr. */
        }
        else
        {
          errno = 0;
        }
      } while (errno && errno != EINTR);

此BTW

   do{
        errno = 0;
        execve("./child", child_arg, NULL);
    }while(errno);

仅作为exec*()函数族的成员,仅在出错时返回。因此,在测试while的条件时,尽管设置了execve() ,但errno 失败了。这里的初始errnr = 0;设置也没有用。

答案 1 :(得分:0)

您的程序存在许多问题。它通过从信号处理程序中调用exitfreemsgctl来调用未定义的行为。 开放组基本规范Signal Actions部分中的表列出了可以从信号处理程序中安全调用的函数。在大多数情况下,您只想从处理程序中切换“正在运行”标志,并使主循环运行直到被告知退出。类似于以下简单示例:

#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


/* this will be set when the signal is received */
static sig_atomic_t running = 1;


void
sig_handler(int signo, siginfo_t *si, void *context)
{
    running = 0;
}


int
main(int argc, char *argv[])
{
    int rc;
    struct sigaction sa;

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = &sig_handler;
    rc = sigaction(SIGINT, &sa, NULL);
    if (rc < 0) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    printf("Waiting for SIGINT\n");
    while (running) {
        printf("... sleeping for 10 seconds\n");
        sleep(10);
    }
    printf("Signal received\n");

    return 0;
}

我也在repl.it上组织了一个更为复杂的会议。

另一个问题是您假设errno在所有函数调用中都保留零值。可能是这种情况,但是您应该假设的关于errno的唯一事情是,当库函数返回失败代码时,它将被分配一个值-例如,read返回-1并将errno设置为表明错误的内容。调用C运行时库函数的常规方法是检查返回值,并在适当时咨询errno

int bytes_read;
unsigned char buf[128];

bytes_read = read(some_fd, &buf[0], sizeof(buf));
if (bytes_read < 0) {
    printf("read failed: %s (%d)\n", strerror(errno), errno);
}

您的应用程序可能正在循环,因为父母的行为不正常,没有等待孩子或类似的事情(请参见上文有关未定义的行为)。如果在子级退出之前删除了消息队列,则msgrcv调用将失败,并将errno设置为EINVAL。在检查msgrcv之前,应先检查errno是否失败。当子进程遇到msgrcv等于errno的{​​{1}}失败时,子进程也应终止循环,因为这是一个终端条件-匿名消息队列停止后将永远无法重新创建存在。

相关问题