进程A:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>
int msgid;
int msgBpid;
struct {
long mtype;
pid_t pid;
} msg;
void sigusr2_handler(int sig) {
//读取消息
msgrcv(msgid, &msg, sizeof(msg.pid), 0, 0);
printf("Received message from process B. PID: %d\n", msg.pid);//打印进程B的pid
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
}
int main() {
//创建一个消息队列
key_t key = ftok(".", 10);
msgid = msgget(key, IPC_CREAT | 0666);
if(msgid == -1)//判断创建是否出错
{
fprintf(stderr,"msgget error,error:%d,%s\n",errno,strerror(errno));
return -1;
}
//输入进程B的pid
printf("please input msgB pid:");
scanf("%d",&msgBpid);
// 发送SIGUSR1信号给进程B
kill(msgBpid, SIGUSR1);
//信号响应接口
signal(SIGUSR2, sigusr2_handler);
//获取进程A的pid;创建消息队列的id
printf("Process A (PID: %d) ", getpid());
while (1);
return 0;
}
进程B:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>
int msgid;
int msgApid;
struct {
long mtype;
pid_t pid;
} msg;
void sigusr1_handler(int sig) {
//发送消息
msg.mtype = 1;
msg.pid = getpid();
msgsnd(msgid, &msg, sizeof(msg.pid), IPC_NOWAIT);
}
int main() {
//创建消息队列
key_t key = ftok(".", 10);
msgid = msgget(key, IPC_CREAT | 0666);
if(msgid == -1)//判断创建是否出错
{
fprintf(stderr,"msgget error,error:%d,%s\n",errno,strerror(errno));
return -1;
}
//信号响应接口
signal(SIGUSR1, sigusr1_handler);
//输入进程A的pid
printf("please input msgA pid:");
scanf("%d",&msgApid);
// 发送SIGUSR2信号给进程A
kill(msgApid, SIGUSR2);
//打印进程B的pid;打开消息队列的id
// printf("Process B (PID: %d)", getpid());
while (1);
return 0;
}
注意:利用ps -ef命令可查看进程中的pid。
标签:队列,msgid,pid,int,消息,key,msg,include From: https://www.cnblogs.com/lwj294/p/18218097