Linux发送与接收信息

本文提供了一组使用消息队列进行进程间通信的C语言示例代码,包括消息发送和接收两端的实现细节。通过具体代码展示了如何创建、使用及销毁消息队列,适用于希望了解或实践消息队列机制的学习者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

receive:

ExpandedBlockStart.gifView Code
#include <sys/types.h>
#include 
<sys/ipc.h>
#include 
<sys/msg.h>
#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<unistd.h>
#include 
<string.h>

#define BUFFER_SIZE  512

struct message
{
    
long msg_type;
    
char msg_text[BUFFER_SIZE];
};

int main()
{
    
int qid;
    key_t key;
    
struct message msg;
    
    
if((key=ftok(".",'a'))==-1)
    {
        perror(
"ftok");
        exit(
1);
    }

    
if((qid=msgget(key,IPC_CREAT|0666))==-1)
    {
        perror(
"msgget");
        exit(
1);
    }

    printf(
"Open queue %d",qid);

    
do
    {
        memset(msg.msg_text,
0,BUFFER_SIZE);
        
if(msgrcv(qid,(void*)&msg,BUFFER_SIZE,0,0)<0)
        {
            perror(
"msgrcv");
            exit(
1);
        }

        printf(
"The message from process %d : %s",(int)msg.msg_type,msg.msg_text);
        
    }
while(strncmp(msg.msg_text,"quit",4));

    
if((msgctl(qid,IPC_RMID,NULL))<0)
    {
        perror(
"msgctl");
        exit(
1);
    }
    
    exit(
0);
    
}

 

send:

 

ExpandedBlockStart.gifView Code
#include <sys/types.h>
#include 
<sys/ipc.h>
#include 
<sys/msg.h>
#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<unistd.h>
#include 
<string.h>

#define BUFFER_SIZE 512


struct message{
    
long msg_type;
    
char msg_text[BUFFER_SIZE];
};

int main()
{
    
int qid;
    key_t key;
    
struct message msg;
    
    
if((key=ftok(".",'a'))==-1)
    {
        perror(
"ftok");
        exit(
1);
    }

    
if((qid=msgget(key,IPC_CREAT|0666))==-1)
    {
        perror(
"msgget");
        exit(
1);
    }

    printf(
"Open queue %d\n",qid);
    
    
while(1)
    {
        printf(
"Enter some message to the queue:");
        
if((fgets(msg.msg_text,BUFFER_SIZE,stdin))==NULL)
        {
            puts(
"No message");
            exit(
1);
        }
        msg.msg_type
=getpid();
        
        
if((msgsnd(qid,&msg,strlen(msg.msg_text),0))<0)
        {
            perror(
"message posted");
            exit(
1);
        }

        
if(strncmp(msg.msg_text,"quit",4)==0)
        {
            
break;
        }

    }
    exit(
0);
}


 

gcc 两者

 #运行接收

./msgcrv 

#运行发送 

./msgsnd

#open two console to see the effect

转载于:https://www.cnblogs.com/no7dw/archive/2011/05/18/2049495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值