sigaction处理程序不会关闭该进程

时间:2013-06-10 14:02:24

标签: c asynchronous signals

我有以下sigaction处理程序代码

void signal_term_handler(int sig)
{
    int rc = async_lockf(pid_file, F_UNLCK);
    if(rc) {
        char piderr[] = "PID file unlock failed!\n";
        write(STDOUT_FILENO, piderr, (sizeof(piderr))-1);
    }
    close(pid_file);
    char exitmsg[] = "EXIT Daemon:TERM signal Received!\n";
    write(STDOUT_FILENO, exitmsg, (sizeof(exitmsg))-1);
    _exit(EXIT_SUCCESS); //async-signal-save exit
}

上述函数中的所有函数调用都是异步信号保存。即使async_lockf()也是异步信号保存:

/*
 * The code of async_lockf is copied from eglibc-2.11.3/io/lockf.c
 * The lockf.c is under the terms of the GNU Lesser General Public
 * Copyright (C) 1994,1996,1997,1998,2000,2003 Free Software Foundation, Inc.
 * This file is part of the GNU C Library.
*/

int async_lockf(int fd, int cmd)
{
    struct flock fl = {0};

    /* async_lockf is always relative to the current file position.  */
    fl.l_whence = SEEK_CUR;
    fl.l_start = 0;
    fl.l_len = 0;

    switch (cmd)
    {
        case F_TEST:
            /* Test the async_lock: return 0 if FD is unlocked or locked by this process;
             return -1, set errno to EACCES, if another process holds the lock.  */
            fl.l_type = F_RDLCK;
            if (fcntl (fd, F_GETLK, &fl) < 0)
                return -1;
            if (fl.l_type == F_UNLCK || fl.l_pid == getpid ())
                return 0;
            errno = EACCES;
            return -1;

        case F_ULOCK:
            fl.l_type = F_UNLCK;
            cmd = F_SETLK;
            break;
        case F_LOCK:
            fl.l_type = F_WRLCK;
            cmd = F_SETLK;
            break;
        case F_TLOCK:
            fl.l_type = F_WRLCK;
            cmd = F_SETLK;
            break;

        default:
            errno = EINVAL;
            return -1;
    }

    /* async_lockf() is a cancellation point but so is fcntl() if F_SETLKW is
     used.  Therefore we don't have to care about cancellation here,
     the fcntl() function will take care of it.  */
    return fcntl (fd, cmd, &fl);
}

如果我执行kill -15命令,sigaction处理程序应该关闭应用程序,但有时我会让processus运行而不会退出。这很少发生。例如,如果我启动应用程序,然后我以kill -15 1000次停止,此行为将仅发生约5次

对这种奇怪行为的任何解释?为什么我的申请不存在?特别是我使用异步信号保存功能(_exit())来关闭进程

1 个答案:

答案 0 :(得分:1)

要查看正在发生的情况,请尝试将stracegdb附加到流程中,并查看其中的位置。我最好的猜测是,在执行阻塞操作时,您有代码屏蔽信号(sigprocmask),从而阻止信号处理程序运行。