linux c消息队列实现进程通信简单实例

代码

//写进程
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<unistd.h>
#include<string.h>

struct msg
{
    long msg_types;
    char msg_buf[512];
};

int main()
{
    int qid;
    int pid;
    int len;
    struct msg pmsg;

    pmsg.msg_types = getpid();

    sprintf(pmsg.msg_buf,"hello! this is %d\n",getpid());

    len = strlen(pmsg.msg_buf);

    qid = msgget(IPC_PRIVATE,IPC_CREAT|0666);

    msgsnd(qid,&pmsg,len,0);

    printf("successfully send a massage to queue:%d\n",qid);

    return 0;

}
//读进程
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define BUFSZ 4096

struct msg
{
    long msg_types;
    char msg_buf[512];
};

int main(int argc,char ** argv)
{
    int qid;
    int len;
    struct msg pmsg;

    if(argc != 2)
    {
        perror("argc");
    }

    qid = atoi(argv[1]);

    len = msgrcv(qid,&pmsg,BUFSZ,0,0);

    if(len > 0)
    {
        pmsg.msg_buf[len] = '\0';

        printf("qid %d\n",qid);
        printf("msg type %ld\n",pmsg.msg_types);
        printf("msg text %s\n",pmsg.msg_buf);
    }
    else if(len == 0)
    {
        printf("no massage!\n");
    }
    else
    {
        perror("msgrcv error
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,展示了如何在Linux进程之间使用消息队列进行通信。 发送方进程: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/msg.h> #define MSG_SIZE 256 struct msg_buffer { long msg_type; char msg_text[MSG_SIZE]; }; int main() { key_t key; int msg_id; struct msg_buffer message; // 创建一个唯一的key key = ftok("msgq.txt", 'A'); // 创建消息队列 msg_id = msgget(key, 0666 | IPC_CREAT); // 设置消息类型 message.msg_type = 1; // 设置消息内容 strcpy(message.msg_text, "Hello from sender!"); // 发送消息 msgsnd(msg_id, &message, sizeof(message), 0); printf("Message sent: %s\n", message.msg_text); return 0; } ``` 接收方进程: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/msg.h> #define MSG_SIZE 256 struct msg_buffer { long msg_type; char msg_text[MSG_SIZE]; }; int main() { key_t key; int msg_id; struct msg_buffer message; // 创建一个唯一的key key = ftok("msgq.txt", 'A'); // 获取消息队列 msg_id = msgget(key, 0666 | IPC_CREAT); // 接收消息 msgrcv(msg_id, &message, sizeof(message), 1, 0); printf("Message received: %s\n", message.msg_text); // 删除消息队列 msgctl(msg_id, IPC_RMID, NULL); return 0; } ``` 这两个进程可以在同一台计算机上运行,也可以在不同的计算机上运行。在发送方进程中,首先创建一个唯一的key,然后使用该key创建一个新的消息队列。接下来,设置消息类型为1,将消息内容设置为“Hello from sender!”,并将消息发送到消息队列中。 在接收方进程中,使用与发送方进程相同的key获取消息队列。然后使用msgrcv函数接收消息,并将消息类型设置为1,这与发送方进程中设置的消息类型相同。最后,打印接收到的消息,然后使用msgctl函数删除消息队列

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值