进程间通信:信号

http://www.cnblogs.com/hoys/archive/2012/08/19/2646377.html

#include <signal.h>

typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler));

int sigaction(int signum,const struct sigaction *act,struct sigaction *oldact));
sigaction函数用于改变进程接收到特定信号后的行为。该函数的第一个参数为信号的值,可以为除SIGKILL及SIGSTOP外的任何一个特定有效的信号(为这两个信号定义自己的处理函数,将导致信号安装错误)。第二个参数是指向结构sigaction的一个实例的指针,在结构sigaction的实例中,指定了对特定信号的处理,可以为空,进程会以缺省方式对信号处理;第三个参数oldact指向的对象用来保存返回的原来对相应信号的处理,可指定oldact为NULL。如果把第二、第三个参数都设为NULL,那么该函数可用于检查信号的有效性。

SA_NODEFER:  一般情况下, 当信号处理函数运行时,内核将阻塞该给定信号。但是如果设置了 SA_NODEFER标记, 那么在该信号处理函数运行时,内核将不会阻塞该信号
SA_RESETHAND:当用户注册的信号处理函数被执行过一次后,该信号的处理函数被设为系统默认的处理函数。

SA_SIGINFO 提供附加信息,一个指向siginfo结构的指针以及一个指向进程上下文标识符的指针


发送信号的主要函数有:kill()、raise()、 sigqueue()、alarm()、setitimer()以及abort()。

#ifndef T_DESC
#define T_DESC(x, y)   (y)
#endif

#if T_DESC("TU1", 1)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <stdarg.h>

void sig_handler(int signumber)
{
    printf("catch signal %d", signumber);
}

int tu1_proc(void)
{
    char buffer1[128];
    struct sigaction act;
    
    if(signal(SIGUSR1, &sig_handler)==SIG_ERR)
    {
        printf("failed to register signal handler for SIGINT!
");
    }
    
    act.sa_handler = sig_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    if(sigaction(SIGUSR2, &act, NULL)==-1)
    {
        printf("failed to register signal handler for SIGALRM!
");
    }

    printf("pid of This Process: %d", getpid());

    for( ; ; )
    {
        printf("
 input dest pid: ");
        fgets(buffer1, sizeof(buffer1), stdin);

        if (atoi(buffer1) > 0) {
            kill(atoi(buffer1), SIGUSR1);
            kill(atoi(buffer1), SIGUSR2);
        }
    }

    return 0;
}

#endif

#if T_DESC("global", 1)

void usage()
{
    printf("
 Usage: <cmd> <tu> <p1> <...>");
    printf("
   1 -- signal send test");
    printf("
");
}

int main(int argc, char **argv)
{
    int ret;
    
    if(argc < 2) {
        usage();
        return 0;
    }

    int tu = atoi(argv[1]);
    if (tu == 1) ret = tu1_proc();
    
    return ret;
}
#endif
原文地址:https://www.cnblogs.com/soul-stone/p/6683141.html