C中的消息队列:实现2路通信 [英] message queue in C: implementing 2 way comm
问题描述
我是C语言的学生和初学者.我想使用C linux中的消息队列实现双向通讯.我需要两个队列还是只有一个队列才能完成此任务?
I am a student and a begineer in C. I want to implement 2 way communication using message queue in C linux. Do I need two queues or only one to get this done?
我还想知道是否可以将数据(显示为代码)发送到另一个进程,或者我需要将其声明为字符数组.
Also I would like to know can I send data(shown in code) to another process or i need to declare it as a character array.
typedef struct msg1
{
int mlen;
char *data;
}M1;
typedef struct msgbuf
{
long mtype;
M1 *m;
} message_buf;
先谢谢您了:)
推荐答案
Also I would like to know can I send data(shown in code) to another process or i need to declare it as a character array
是的,您可以将数据发送到另一个进程
yes you can send data to another process
喜欢
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#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("%[^\n]",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
else
printf("Message Sent\n");
exit(0);
}
//IPC_msgq_rcv.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#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\n", rcvbuffer.mtext);
exit(0);
}
如果您了解消息队列,则可以使用Message Queue进行进程间通信.
If you know about message queue, then Message Queue is used for inter-process communication.
对于多个进程之间的双向通信,您还需要多个消息队列
Also for two-way communication between multiple processes you need multiple message queue
这篇关于C中的消息队列:实现2路通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!