zoukankan      html  css  js  c++  java
  • 信号专题练习

    一、基本语法

    #include <unistd.h>
    #include <stdio.h>
    #include <signal.h>
    
    void func(int sig)                      // 信号处理器程序
    {
            printf("capture signal %d
    ", sig);
    }
    
    void testSigaction()    
    {
            /* 设置sigaction()系统调用中的act参数 */
            struct sigaction act;    
            act.sa_handler= func;
            act.sa_flags = SA_RESETHAND;
            sigaction(SIGINT, &act, NULL);
            kill(getpid(), SIGINT);    
            while(1);
    }
    
    
    int main()
    {
            testSigaction();
            return 0;
    }
    

      

    二、使用SA_SIGINFO标志来完成一个程序。

    #include <stdio.h>
    #include <signal.h>
    #include <unistd.h>
    
    void func(int sig, siginfo_t *info, void *args)
    {
            printf("===== Handle signal %d =====
    ", sig);
            printf("Signal number      :%d
    ", info->si_signo);
            printf("Send Process's PID :%d
    ", info->si_pid);
            printf("Send User's UID    :%d
    ", info->si_uid);
            printf("============================
    ");
    }
    
    
    void testSigaction()
    {
            struct sigaction act;
            act.sa_sigaction = func; // 相比于sa_handler,此能够提供给func一些信号的附加信息
            act.sa_flags = SA_SIGINFO;
            sigemptyset(&act.sa_mask);
            int iRet = sigaction(SIGINT, &act, NULL);
            if (iRet == -1) {
                    perror("fail sigaction");
                    return;
            }
            while(1);
    }
    
    int main()
    {
            testSigaction();
            return 0;
    }
    

      

    三、编写一个程序,要求包含信号集、信号掩码、阻塞信号的运用。

    #include <stdio.h>
    #include <signal.h>
    #include <unistd.h>
    
    /* 接受SIGINT信号时,由于其遭到阻塞,故不会执行该信号处理函数 */
    void func(int sig)
    {
            printf("===== Handle signal %d =====
    ", sig);
    }
    
    
    void testSignalBlock()
    {
            sigset_t sigSet, oldSet;                // 信号集
            sigemptyset(&sigSet);                   // 初始化一个未包含任何成员的信号集
            sigaddset(&sigSet, SIGINT);             // 将信号SIGINT添加到信号集sigSet中
            if (sigismember(&sigSet, SIGINT)) {     // 测试SIGINT是否是信号集sigSet的成员
                    printf("SIGINT is blocked!
    ");
            }
            sigprocmask(SIG_SETMASK, &sigSet, &oldSet);     // 将sigSet赋给信号掩码,此时该阻塞才生效
    
            signal(SIGINT, func);                   // signal()系统调用
            while(1);
    }
    
    int main()
    {
            testSignalBlock();
            return 0;
    }
    

      

  • 相关阅读:
    一个封装好的使用完成端口的socket通讯类
    IOCP编程注意事项
    判断socket是否连接(windows socket)
    CRITICAL_SECTION同步易出错的地方
    OCP-1Z0-053-V13.02-43题
    OCP-1Z0-053-V13.02-24题
    OCP-1Z0-053-V13.02-490题
    OCP-1Z0-053-V12.02-456题
    OCP-1Z0-053-V12.02-447题
    OCP-1Z0-053-V13.02-710题
  • 原文地址:https://www.cnblogs.com/xzxl/p/8586609.html
Copyright © 2011-2022 走看看