Linux下进程通信之消息队列
2013-05-08 16:46
489 查看
read date from message: msg_r.c
write data to messag: msg_w.c
msgsnd与msgrec在接受和发送数据类型要注意,不然变异很容易出错
1.传送的类型
2.传送和接收的数据空间
#include<stdlib.h> #include<stdio.h> #include<string.h> #include<errno.h> #include<unistd.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #define BUFFSIZE 2050 struct my_msg { long int l_msg_type; char sz_msg_text[BUFFSIZE]; }; int main(void) { int n_run = 1; int n_msgid; struct my_msg st_msg; long int l_rec_type; n_msgid = msgget((key_t)1234,0666|IPC_CREAT); if(n_msgid==-1) { fprintf(stderr,"create msg failed: %s!\n",strerror(errno)); exit(EXIT_FAILURE); } while(n_run) { if(msgrcv(n_msgid,(void*)&st_msg,BUFFSIZE,l_rec_type,0)==-1) { if(errno==EAGAIN) { printf("No data to read!\n"); sleep(1); } else { fprintf(stderr,"receive data error: %s !\n",strerror(errno)); exit(EXIT_FAILURE); } } printf("You Write data: %s",st_msg.sz_msg_text); if(strncmp(st_msg.sz_msg_text,"end",3)==0) { n_run=0; } } if(msgctl(n_msgid,IPC_RMID,0)==-1) { fprintf(stderr,",remove msg failed:%s\n",strerror(errno)); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
write data to messag: msg_w.c
#include<stdlib.h> #include<stdio.h> #include<string.h> #include<errno.h> #include<unistd.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #define BUFFSIZE 1024 #define MAX_TEXT 2048 struct my_msg { long int l_msg_type; char sz_msg_text[MAX_TEXT]; }; int main(void) { int n_run = 1; int n_msgid; struct my_msg st_msg; long int l_rec_type; char sz_buff[BUFFSIZE]; n_msgid = msgget((key_t)1234,0666|IPC_CREAT); if(n_msgid==-1) { fprintf(stderr,"create msg failed: %s!\n",strerror(errno)); exit(EXIT_FAILURE); } while(n_run) { printf("please input data:"); fgets(sz_buff,BUFFSIZE,stdin); st_msg.l_msg_type=1; strcpy(st_msg.sz_msg_text,sz_buff); //st_msg.sz_msg_text=sz_buff; if(msgsnd(n_msgid,(void*)&st_msg,MAX_TEXT,0)==-1) { fprintf(stderr,"send data error: %s!\n",strerror(errno)); exit(EXIT_FAILURE); } if(strncmp(st_msg.sz_msg_text,"end",3)==0) { n_run=0; } } exit(EXIT_SUCCESS); }
msgsnd与msgrec在接受和发送数据类型要注意,不然变异很容易出错
1.传送的类型
2.传送和接收的数据空间
相关文章推荐
- 学习笔记——操作系统_Linux进程通信之消息队列
- linux消息队列进程通信
- Linux:进程通信之消息队列Message实例
- [转]Linux进程通信之POSIX消息队列
- Linux--进程通信之消息队列的双向通信
- Linux C程序练习(3)进程通信之pipe、fifo、消息队列
- linux消息队列进程通信
- Linux消息队列进程通信的介绍
- Linux:进程通信之消息队列Message实例
- UNIX/LINUX编程学习之进程通信--消息队列
- linux进程通信-消息队列
- linux进程通信--消息队列
- msgget();msgsnd();msgrcv();msgctl(); 消息队列 Linux进程间的通信方式之消息队列
- linux进程通信之消息队列
- linux进程通信之消息队列
- Linux — IPC进程通信之消息队列详解
- linux进程通信---消息队列
- Linux进程通信之消息队列的双向通信
- Linux进程通信之POSIX消息队列
- Linux进程间的通信方式:运用消息队列通信