您的位置:首页 > 理论基础 > 计算机网络

linux网络编程之System V 消息队列:消息队列实现回射客户/服务器和 msgsnd、msgrcv 函数

2016-06-18 10:52 701 查看
#include<stdlib.h>
#include <stdio.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/types.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>

#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)

#define MSGMAX 8192

struct mymsgbuf
{
long mtype;
char mtext[MSGMAX];
};

void echo_ser(int msgid)
{
struct mymsgbuf msg;
memset(&msg, 0, sizeof(msg));
int nrcv = 0;
while (1)
{

if ((nrcv = msgrcv(msgid, &msg, MSGMAX, 1, 0)) < 0)
;
int pid = *((int *)msg.mtext);
fputs(msg.mtext + 4, stdout);
msg.mtype = pid;
msgsnd(msgid, &msg, nrcv, 0);
memset(&msg, 0, sizeof(msg));

}
}

int main(int argc, char *argv [])
{
int msgid;
msgid = msgget(1234, IPC_CREAT | 0666);
if (msgid == -1)
ERR_EXIT("msgget");

echo_ser(msgid);

return 0;
}
<pre name="code" class="cpp">#include<stdio.h>#include<stdlib.h>#include<sys/ipc.h>#include<sys/msg.h>#include<sys/types.h>#include<unistd.h>#include<errno.h>#include<string.h>#define ERR_EXIT(m) \do { \perror(m); \exit(EXIT_FAILURE); \} while(0)#define MSGMAX 8192struct mymsgbuf{long mtype;char mtext[MSGMAX];};void echo_cli(int msgid){int nrcv;int pid = getpid();struct mymsgbuf msg;memset(&msg, 0, sizeof(msg));msg.mtype = 1;*((int *)msg.mtext) = pid;while (fgets(msg.mtext + 4, MSGMAX, stdin) != NULL){if (msgsnd(msgid, &msg, 4 + strlen(msg.mtext + 4), IPC_NOWAIT) < 0)ERR_EXIT("msgsnd");memset(msg.mtext + 4, 0, MSGMAX - 4);if ((nrcv = msgrcv(msgid, &msg, MSGMAX, pid, 0)) < 0)ERR_EXIT("msgsnd");fputs(msg.mtext + 4, stdout);memset(msg.mtext + 4, 0, MSGMAX - 4);}}int main(int argc, char *argv []){int msgid;msgid = msgget(1234, 0);if (msgid == -1)ERR_EXIT("msgget");echo_cli(msgid);return 0;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: