linux 进程通信

本文提供了一组基于消息队列实现进程间通信的示例代码。包括发送端(message_send.c)和接收端(message_get.c),展示了如何使用msgget、msgsnd及msgrcv等系统调用进行消息传递。

message_send.c


#include<unistd.h>

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<sys/msg.h>
#define MAX_TEXT  512


struct msg_st
{
  long int msg_type;
  char text[MAX_TEXT];
};

  int main()
{
int runing =1;
struct msg_st data;
char buffer[BUFSIZ];
int msgid=-1;

msgid=msgget((key_t)1234,0666 | IPC_CREAT);
if(msgid==-1)
{
 fprintf(stderr,"msgget failed with error: \n");
exit(EXIT_FAILURE);
}
while(runing)
{
   printf("Please Enter some text:");
   fgets(buffer,BUFSIZ,stdin);
    data.msg_type=1;
    strcpy(data.text,buffer);
if(msgsnd(msgid,(void*)&data,MAX_TEXT,0)==-1)
        {
   fprintf(stderr,"msgsend failed \n");
   exit(EXIT_FAILURE);
}
if(strncmp(buffer,"end",3)==0) runing=0;
sleep(1);
}
exit(EXIT_SUCCESS);

}


message_get.c

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<sys/msg.h>


struct msg_st
{
  long int msg_type;
 char text[BUFSIZ];
};

 int main()
   {
int running=1;
int msgid=-1;
struct msg_st data;
long int msgtype=0;

msgid=msgget((key_t)1234,0666 | IPC_CREAT);
 if(msgid==-1)
  {
fprintf(stderr,"message failed with error: %d \n",errno);
exit(EXIT_FAILURE);
  }
while(running)
{
if(msgrcv(msgid,(void*)&data,BUFSIZ,msgtype,0)==-1)
                                      {
fprintf(stderr,"msgrcv failed with erron: %d \n",errno);
 exit(EXIT_FAILURE);
      }
printf("You wrote:%s\n",data.text);
if(strncmp(data.text,"end",3)==0)  running=0;
}
if(msgctl(msgid,IPC_RMID,0)==-1)
                                   {
fprintf(stderr,"msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
  }
exit(EXIT_SUCCESS);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值