Unix/Linux进程间通信——(System V)消息队列
2013-12-27 15:58
267 查看
System V消息队列实例:
/* http://beej.us/guide/bgipc/examples/kirk.c */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct my_msgbuf { long mtype; char mtext[200]; }; int main(void) { struct my_msgbuf buf; int msqid; key_t key; if ((key = ftok("kirk.c", 'B')) == -1) { perror("ftok"); exit(1); } if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) { perror("msgget"); exit(1); } printf("Enter lines of text, ^D to quit:\n"); buf.mtype = 1; /* we don't really care in this case */ while(fgets(buf.mtext, sizeof(buf.mtext), stdin) != NULL) { int len = strlen(buf.mtext); /* ditch newline at end, if it exists */ if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0'; if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */ perror("msgsnd"); } if (msgctl(msqid, IPC_RMID, NULL) == -1) { perror("msgctl"); exit(1); } return 0; }
/* http://beej.us/guide/bgipc/examples/spock.c */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct my_msgbuf { long mtype; char mtext[200]; }; int main(void) { struct my_msgbuf buf; int msqid; key_t key; if ((key = ftok("kirk.c", 'B')) == -1) { /* same key as kirk.c */ perror("ftok"); exit(1); } if ((msqid = msgget(key, 0644)) == -1) { /* connect to the queue */ perror("msgget"); exit(1); } printf("spock: ready to receive messages, captain.\n"); for (;;) { /* Spock never quits! */ if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) { perror("msgrcv"); exit(1); } printf("spock: \"%s\"\n", buf.mtext); } return 0; }
相关文章推荐
- Unix/Linux 进程间通信之消息队列应用实例
- linux 进程间通信--systemV 消息队列 实例
- UNIX/Linux进程间通信IPC系列(四)消息队列
- 【原创】《Linux高级程序设计》杨宗德著 - 进程管理与程序开发 - System V进程间通信之消息队列 分类: Linux --- 应用程序设计 2014-11-11 13:16 71人阅读 评论(0) 收藏
- linux进程间通信---消息队列
- Linux进程间通信-消息队列
- Linux 进程间通信之 消息队列
- linux进程间通信消息队列
- linux进程间通信(posix消息队列)实例
- Linux的进程间通信-消息队列
- System V 进程间通信(IPC)之System V 消息队列
- Linux环境进程间通信(三)消息队列
- 进程间通信 之 消息队列(Linux)
- Linux进程间通信(二)——共享内存、消息队列
- linux网络编程之System V 消息队列(一):消息队列内核结构和msgget、msgctl 函数
- Linux-进程间通信(二、消息队列)
- Linux进程间通信——消息队列
- Linux中进程间通信——消息队列
- Linux进程间通信——使用消息队列
- Linux进程间通信-消息队列