• 进程通信(2) ----- 信号



    一、实验目的

    1.了解进程通信间的信号机制
    2.掌握进程通信间的信号编程模型

    二、实验内容

    信号是通信量最小的一种进程间通信形式,也用于内核与进程间的通信,信号是软件中断,它传递异步信号。本次实验内容如下:
    1.使用kill函数杀死另一进程
    2.信号的处理
    3.阻塞信号
    4.检测挂起的信号,设置信号处理程序

    三、实验要求

    实验需提前准备一台PC机,并在PC机上搭建Linux Ubuntu环境。

    四、实验步骤及操作

    1.打开Linux系统,新建终端
    2.新建文件
    3.编写代码
    4.编译运行

    五、程序源码

    1. 信号发送 fkill.c

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(void)
    {
         pid_t child;
         int errret;
     
         if((child = fork()) < 0) {
    	    perror("fork");
    	    exit(EXIT_FAILURE);
         } else if(child == 0) {	/* in the child process */
    	    sleep(30);//使当前进程睡眠30s
         } else {			/* in the parent */
    	    /* 发送一个被忽略的信号 */
    	    printf("sending SIGCHLD to %d\n", child);//SIGCHLD标识子进程停止或结束的信号
    	    errret = kill(child, SIGCHLD);    //向child进程号发送SIGCHLD信号 
    	    if(errret < 0)
    	       perror("kill:SIGCHLD");
    	    else
    	       printf("%d still alive\n", child);
    
    	    /* now murder the child */
    	    printf("killing %d\n", child);
    	    if((kill(child, SIGTERM)) < 0)//SIGTERM是kill发送的软件结束信号
    	       perror("kill:SIGTERM");
    	    /* have to wait to reap the status */
    	    waitpid(child, NULL, 0 );   //回收子进程 
         }
         exit(EXIT_SUCCESS);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    在这里插入图片描述

    2. 信号监控 mysignal.c

    #include 
    #include 
    #include 
    #include 
    void my_func(int sign_no)
    {
    	if(sign_no==SIGINT)    //程序终止(interrupt)信号, 在用户键入INTR字符(通常是Ctrl-C)时发出,用于通知前台进程组终止进程
    		printf("I have get SIGINT\n");
    	else if(sign_no==SIGQUIT)
    		printf("I have get SIGQUIT\n"); //SIGQUIT 信号对应的 signo = 03,表示用户从键盘按下quit键,即 ctrl+\ ,
    		                                //进程在收到 SIGQUIT 退出时会产生 core 文件,在这个意义上类似于一个程序错误信号。
    }
    int main()
    {
    	printf("Waiting for signal SIGINT or SIGQUIT \n ");
    	signal(SIGINT, my_func);      //参数一:处理信号   参数二:处理方式 
    	signal(SIGQUIT, my_func);
    	pause();   //令目前的进程暂停(进入睡眠状态), 直到被信号(signal)所中断
    	exit(0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

  • 相关阅读:
    开发潜能52个方法
    Python对象序列化
    【无标题】
    Jenkins+Svn+Docker搭建持续集成环境 自动部署
    索引初识
    C++迭代器失效
    RootSIFT---SIFT图像特征的扩展
    指令手册术语缩写
    ros发布节点和接收节点的编写
    『忘了再学』Shell基础 — 10、Bash中的特殊符号(二)
  • 原文地址:https://blog.csdn.net/Dustinthewine/article/details/128068184