linux 双向消息队列,C中的消息队列:实现2路通信

另外我想知道我可以将数据(以代码显示)发送到另一个进程,或者我需要将其声明为字符数组

是的,您可以将数据发送到另一个进程

喜欢

#include

#include

#include

#include

#include

#include

#define MAXSIZE 128

void die(char *s)

{

perror(s);

exit(1);

}

struct msgbuf

{

long mtype;

char mtext[MAXSIZE];

};

main()

{

int msqid;

int msgflg = IPC_CREAT | 0666;

key_t key;

struct msgbuf sbuf;

size_t buflen;

key = 1234;

if ((msqid = msgget(key, msgflg )) < 0) //Get the message queue ID for the given key

die("msgget");

//Message Type

sbuf.mtype = 1;

printf("Enter a message to add to message queue : ");

scanf("%[^

]",sbuf.mtext);

getchar();

buflen = strlen(sbuf.mtext) + 1 ;

if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)

{

printf ("%d, %d, %s, %d

", msqid, sbuf.mtype, sbuf.mtext, buflen);

die("msgsnd");

}

else

printf("Message Sent

");

exit(0);

}

//IPC_msgq_rcv.c

#include

#include

#include

#include

#include

#define MAXSIZE 128

void die(char *s)

{

perror(s);

exit(1);

}

typedef struct msgbuf

{

long mtype;

char mtext[MAXSIZE];

} ;

main()

{

int msqid;

key_t key;

struct msgbuf rcvbuffer;

key = 1234;

if ((msqid = msgget(key, 0666)) < 0)

die("msgget()");

//Receive an answer of message type 1.

if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)

die("msgrcv");

printf("%s

", rcvbuffer.mtext);

exit(0);

}

如果您了解消息队列,则Message Queue用于进程间通信.

此外,对于多个进程之间的双向通信,您需要多个消息队列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值