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;}
相关文章推荐
- HttpClient+jsoup实现网页数据抓取和处理
- neural networks and deep learning(Michael Nielsen)笔记(1)
- 通信协议:HTTP、TCP、UDP
- 基于UDP协议的网络程序
- 深入理解HTTP Session
- Volley网络请求封装之LruCache源码分析
- Wireshark和TcpDump抓包分析心得
- Linux基础: 网络命令和进程管理
- Deep Learning(深度学习)之(五)神经网络训练中的高效BP(反向传播算法)
- TCP/IP七层网络结构
- 流量整形,延迟以及ACK丢失对TCP发送时序的影响
- HTTP状态
- 给tcpdump加点颜色看看
- HTTPClient
- android 获取网络视频缩略图
- DZ论坛伪静态加HTTP跳转HTTPS的IIS配置文件
- AFNetworking3.0的使用 与2.0的区别
- 从C10K到C10M高性能网络的探索与实践
- 一、TCP C/S:客户端、服务器程序示例
- 二、TCP C/S:正常启动