Linux进程之间通信 信号

  • 2) SIGINT
    程序终止(interrupt)信号, 在用户键入INTR字符(通常是Ctrl-C)时发出,用于通知前台进程组终止进程。
     
  • 3) SIGQUIT
    和SIGINT类似, 但由QUIT字符(通常是Ctrl-\)来控制. 进程在因收到SIGQUIT退出时会产生core文件, 在这个意义上类似于一个程序错误信号。
     
  • 15) SIGTERM
    程序结束(terminate)信号, 与SIGKILL不同的是该信号可以被阻塞和处理。通常用来要求程序自己正常退出,shell命令kill缺省产生这个信号。如果进程终止不了,我们才会尝试SIGKILL。
     
  • 19) SIGSTOP
    停止(stopped)进程的执行. 注意它和terminate以及interrupt的区别:该进程还未结束, 只是暂停执行. 本信号不能被阻塞, 处理或忽略. 

代码

  • 子进程运行到3的时候,会停止,父进程唤醒子进程,子进程接着运行,当子进程到4的时候,中断退出,所有的进程全部结束
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <wait.h>

int main() {
    pid_t pid = 0;
    int ret;
    int i =1;
    if ((pid = fork()) < 0) {
        perror("fork error!\n");
        exit(1);
    }
    if (pid == 0) {
        printf("children pid = %d\n", getpid());
        //raise(SIGINT)
        for (i = 1; i < 10; i++) {
            sleep(1);
            printf("children printf %d ...\n", i);
            if (i == 3) {
                printf("stop!\n");
                raise(SIGSTOP);//进程停止信号
            }
            if (i == 4) {
                printf("contine\n");
                raise(SIGINT);//进程中断信号
            }
            printf("本次id = %d\n", i);
        }
        printf("children exit!\n");
        exit(0);
    } else {
        printf("children process id = %d\n", pid);
        printf("father process pid = %d\n", getpid());
        sleep(5);
        if ((waitpid(pid, nullptr, WNOHANG)) == 0) {
            ret = kill(pid, SIGCONT);
            if (ret == 0)//向子进程发送 继续运行的信号
                printf("信号发送成功 %d \n", pid);
            else {
                perror("信号发送成功 ");
            }
//            printf("\n");
        }
        return 0;
    }
}

  • 前面是要捕捉的信号,后面是针对捕捉的信号对应的处理措施,自己写的一个函数 

定义自己信号处理函数

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <wait.h>

void cancel(int aig){
    printf("当前程序取消了ctrl+C功能\n");
}
int main() {
    signal(SIGINT,cancel);
    while (1){
        printf("*\n");
        sleep(1);
    }
    return 0;
}

代码

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <signal.h>
#include <wait.h>

void ouch(int aig){
    printf("OUCH! - I got signal %d\n",aig);
}
int main() {
    struct sigaction act;
    act.sa_handler = ouch;//设置信号处理函数
    sigemptyset(&act.sa_mask);//初始化信号集
    act.sa_flags = 0;

    sigaction(SIGINT,&act, nullptr);

    while (1){
        printf("Hello World!\n");
        sleep(1);
    }
    return 0;
}
  • 输出结果如下图所示
  • 使用 ctrl + \  停止 

参考链接

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值