/************** 进程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;
}