标签:
消息队列的用法
例1: 两个进程之间传输数据
server.c
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <termios.h> #include <signal.h> #include "msg.h" #define ERROR(flag,msg) if(flag) { printf("%d: ",__LINE__); fflush(stdout); perror(msg); exit(errno); } int main(int argc,char *argv[]) { int qid; int ret; key_t key; struct mymsgbuf msg; key = ftok(PATH_NAME,PROJ_ID); ERROR(key == -1,"ftok"); qid = msgget(key,MSG_FLAG); ERROR(qid == -1,"msgget"); char s[] = "please input msg: "; while(1) { write(STDOUT_FILENO,s,sizeof(s)); ret = read(STDIN_FILENO,msg.mtext,BUF_SIZE); if(strncmp(msg.mtext,"q",1) == 0) break; msg.mtype = SERVER; msg.mtext[ret - 1] = 0; ret = msgsnd(qid,&msg,ret,0); if(ret == -1) break; ret = msgrcv(qid,&msg,BUF_SIZE,CLIENT,0); if(ret == -1) break;
printf("receive from client: %s\n",msg.mtext); } msgctl(qid,IPC_RMID,NULL); return 0; }
client.c
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <termios.h> #include <signal.h> #include "msg.h" #define ERROR(flag,msg) if(flag) { printf("%d: ",__LINE__); fflush(stdout); perror(msg); exit(errno); } int main(int argc,char *argv[]) { int qid; int ret; key_t key; struct mymsgbuf msg; key = ftok(PATH_NAME,PROJ_ID); ERROR(key == -1,"ftok"); qid = msgget(key,MSG_FLAG); ERROR(qid == -1,"msgget"); char s[] = "please input msg: "; while(1) { ret = msgrcv(qid,&msg,BUF_SIZE,SERVER,0); if(ret == -1) break; printf("receive from server: %s\n",msg.mtext); write(STDOUT_FILENO,s,sizeof(s)); ret = read(STDIN_FILENO,msg.mtext,BUF_SIZE); if(strncmp(msg.mtext,"q",1) == 0) break; msg.mtype = CLIENT; msg.mtext[ret - 1] = 0; ret = msgsnd(qid,&msg,ret,0); if(ret == -1) break; } msgctl(qid,IPC_RMID,NULL); return 0; }
另有一个公共的.h文件
#ifndef __MSG_H_ #define __MSG_H_ #include <sys/msg.h> #define BUF_SIZE 256 #define PROJ_ID 32 //#define PATH_NAME "/etc/inittab" //ubuntu has no inittab #define PATH_NAME "/etc/passwd" #define MSG_FLAG (IPC_CREAT | 0600) #define SERVER 1 #define CLIENT 2 struct mymsgbuf { long mtype; char mtext[BUF_SIZE]; }; #endif
编译链接运行(先server后client), 结果如下:
msgctl()对消息队列的控制...略
标签:
原文地址:http://www.cnblogs.com/zhanglong71/p/5087013.html