1.
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct message{
long mytype; //消息标识
char data[100]; //数据
}buf;
int main(int argc, const char *argv[]){
//1.创建键值
key_t key = ftok("./",1);
if(-1 == key){
printf("创建键值失败!\n");
return -1;
}
//创建消息队列
int mes_num = msgget(key,IPC_CREAT | 0777);
if(mes_num == -1){
printf("创建消息队列失败!\n");
return -1;
}
//往消息队列里面发送消息
while(strcmp(buf.data,"end\n")){
printf("请输入一个整数作为标识\n");
scanf("%ld",&buf.mytype);
getchar();
memset(buf.data,0,sizeof(buf.data));
printf("请输入要传输的内容\n");
fgets(buf.data,sizeof(buf.data)-1,stdin);
//默认是阻碍的发送
int send = msgsnd(mes_num,&buf,sizeof(buf),0);
if(-1 == send){
printf("发送失败!\n");
return -1;
}
}
return 0;
}
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct message{
long mytype; //消息标识
char data[100]; //数据
}buf;
int main(int argc, const char *argv[]){
//1.创建键值
key_t key = ftok("./",1);
if(-1 == key){
printf("创建键值失败!\n");
return -1;
}
//创建消息队列
int mes_num = msgget(key,IPC_CREAT | 0777);
if(mes_num == -1){
printf("创建消息队列失败!\n");
return -1;
}
//往消息队列里面发送消息
while(strcmp(buf.data,"end\n")){
printf("请输入一个整数作为接收标识\n");
scanf("%ld",&buf.mytype);
getchar();
memset(buf.data,0,100);
int rcv = msgrcv(mes_num,&buf,sizeof(buf),buf.mytype,0);
if(-1 == rcv){
printf("接收失败!\n");
return -1;
}
printf("接收数据为:%s\n",buf.data);
}
return 0;
}