信号通信:在进程A中自定义信号SIGUSR1的响应接口,进程B向A传递SIGUSR信号,观察A是否响应信号

/*************** 进程A **************/
#include <signal.h>
#include <stdio.h>


int count = 0;

// 自定义函数,接收到SIGUSR1信号后打印count数据
void printf_string(int sig);

int main(){
    while(1){
        signal( SIGUSR1, printf_string);        //收到信号执行printf_string函数
    }
    return 0;
}

void printf_string(int sig){
    printf( "%d\n", count);
    count++;
}




/************** 进程B **************/
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

#define DEST_PID 6720               //进程A的pid                   

int main(){
    // 1、向进程A传递SIGUSR1信号
    int ret = kill( DEST_PID, SIGUSR1);
    if( ret == -1 ){                                    //传递信号失败进行错误处理
        fprintf( stderr, "kill faild,errno=%d,%s", 
                errno, strerror(errno));
    }
    return 0;
}
posted @ 2026-09-12 21:48    阅读(5)  评论(0)    收藏  举报