
消息队列用于双向进程通信
#include #include #include #include #include #include
发布日期:2021-05-10 05:07:21
浏览次数:16
分类:精选文章
本文共 2382 字,大约阅读时间需要 7 分钟。
������������������������������
���������������C������������������������������������������������IPC������������������������������������������������������������
������A���progressA.c)```c#include #include #include #include #include #include #include #define PROGRESS_A 1#define PROGRESS_B 2struct msgbuf { long mtype; // ���������������������������0 char mtext[1024]; // ������������};int main(void) { int ret; int msgid = msgget(0x7777, IPC_CREAT|0777); if (msgid < 0) { printf("������������������������\n"); return -1; } while (1) { msgbuf mbuf; memset(&mbuf, 0, sizeof(mbuf)); mbuf.mtype = PROGRESS_A; // ������������������ memcpy(mbuf.mtext, "hello progressB", sizeof(mbuf.mtext)); if ((ret = msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0)) < 0) { perror("msgsnd"); return -1; } memset(&mbuf, 0, sizeof(mbuf)); if ((ret = msgrcv(msgid, &mbuf, sizeof(mbuf.mtext), PROGRESS_B, 0)) < 0) { perror("msgrcv"); return -1; } printf("������A������������������%s\n", mbuf.mtext); usleep(10000); // ���������1��� } if ((ret = msgctl(msgid, IPC_RMID, NULL)) < 0) { perror("msgctl"); return -1; } return 0;}
������B���progressB.c)
ptal>
```c#include#define PROGRESS_A 1#define PROGRESS_B 2
struct msgbuf {long mtype; // ���������������������������0char mtext[1024]; // ������������};
int main(void) {int ret;int msgid = msgget(0x7777, IPC_CREAT|0777);if (msgid < 0) {printf("������������������������\n");return -1;}
while (1) { msgbuf mbuf; memset(&mbuf, 0, sizeof(mbuf)); mbuf.mtype = PROGRESS_B; memcpy(mbuf.mtext, "hello progressA", sizeof(mbuf.mtext)); if ((ret = msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0)) < 0) { perror("msgsnd"); return -1; } memset(&mbuf, 0, sizeof(mbuf)); if ((ret = msgrcv(msgid, &mbuf, sizeof(mbuf.mtext), PROGRESS_A, 0)) < 0) { perror("msgrcv"); return -1; } printf("������B������������������%s\n", mbuf.mtext); usleep(10000);}if ((ret = msgctl(msgid, IPC_RMID, NULL)) < 0) { perror("msgctl"); return -1;}return 0;
}
���������������������������������������������������������������������A���������������������������B���������������������������������������������������������������������������������������������������������������������