由发送端和接收端组成,这里只是实现了发送端发送接收端接收,相当于半双工吧。编译,运行,发送端输入的数据将会在接收端显示出来,当在发送端输入end之后,发送端和接收端都会退出程序。可以使用ipcs -q命令查看系统中的信号量的状态
发送端源代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#define MAX_TEXT 512
struct my_msg_st
{
int my_msg_type;
char msg_text[MAX_TEXT];
};
typedef struct my_msg_st MSG_ST;
int main()
{
int msgid;
unsigned char running=1;
char buff[MAX_TEXT];
MSG_ST sendmsg;
msgid=msgget((key_t)12345,0777|IPC_CREAT);
if(msgid==-1)
{
perror("msgget");
exit(1);
}
while(running)
{
memset(&sendmsg,0,sizeof(MSG_ST));
printf("please int msg:");
fgets(buff,MAX_TEXT,stdin);
sendmsg.my_msg_type =1;
strcpy(sendmsg.msg_text,buff);
if(msgsnd(msgid,(void *)&sendmsg,MAX_TEXT,0)==-1)
{
perror("msgsnd");
exit(1);
}
if(strncmp(buff,"end",3)==0)
{
printf("the program will exit\n");
running=0;
}
}
return 0;
}
接收端源代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#define MAX_TEXT 512
struct my_msg_rec
{
int my_msg_type;
char msg_text[MAX_TEXT];
};
typedef struct my_msg_rec MSG_REC;
int main()
{
int msgid;
unsigned char running=1;
char buff[MAX_TEXT];
MSG_REC recivemsg;
printf("receive msg process is starting!\n");
printf("the process id=%d\n",getpid());
msgid=msgget((key_t)12345,0777|IPC_CREAT);
if(msgid==-1)
{
perror("msgget");
exit(1);
}
while(running)
{
memset(&recivemsg,0,sizeof(MSG_REC));
//printf("please int msg:");
//fgets(buff,MAX_TEXT,stdin);
//recivemsg.my_msg_type =1;
//strcpy(recivemsg.msg_text,buff);
if(msgrcv(msgid,(void *)&recivemsg,MAX_TEXT,0,0)==-1)
{
perror("msgsnd");
exit(1);
}
printf("the receive msg :%s",recivemsg.msg_text);
if(strncmp(recivemsg.msg_text,"end",3)==0)
{
printf("the program will exit\n");
running=0;
}
}
return 0;
}