消息队列:进程A给进程B发送SIGUSR1信号,进程B收到信号后往消息队列写入自己的进程id并给进程A发送SIGUSR2信号,进程A收到信号后读取数据并打印

/************** 进程A *************/
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>


key_t key;
int msgid;
struct msgbuf{
    long mtype;
    int mtext;
};

void get_sig(int sig){
    key = ftok("/home/yj/Desktop/fork_test.c",'a');      //生成键值
    msgid = msgget(key,IPC_CREAT|0644);                  //创建消息队列
    struct msgbuf buf;                                   //构建消息结构
    msgrcv( msgid, &buf, 4, 1, 0);                       //往消息队列写入数据
    printf( "%d\n", buf.mtext);
}

int main(){
    signal( SIGUSR2, get_sig);                  //注册信号处理函数
    system("killall -SIGUSR1 process_B");       //向进程B发送 SIGUSR1 信号
    while(1);
    return 0;
}




/************* 进程B **************/
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>


key_t key;
int msgid;
pid_t pid ;
struct msgbuf{
    long mtype;
    int mtext;
};

void get_sig(int sig){
    key = ftok("/home/yj/Desktop/fork_test.c",'a');         //生成键值
    msgid = msgget(key,IPC_CREAT|0644);                     //打开目标消息队列
    struct msgbuf buf;                                      //构建消息结构
    pid = getpid();                                         //获取当前进程id
    buf.mtype = 1;
    buf.mtext = pid;
    msgsnd( msgid, &buf, 4, 0);                             //往消息队列里面写入数据
    system("killall -SIGUSR2 process_A");                   //给进程A发送 SIGUSR2 信号
}

int main(){
    signal( SIGUSR1, get_sig);                              //注册信号处理函数
    while(1);
    return 0;
}
posted @ 2026-09-14 23:56    阅读(7)  评论(0)    收藏  举报