linux C 应用消息队列在两个进程间通信
服務:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>
?
struct msg_st
{
?? ?long int msg_type;
?? ?char text[BUFSIZ];
};
?
int main()
{
?? ?int running = 1;
?? ?int msgid = -1;
?? ?struct msg_st data;
?? ?long int msgtype = 0; //注意1
?
?? ?//建立消息隊列
?? ?msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
?? ?if(msgid == -1)
?? ?{
?? ??? ?fprintf(stderr, "msgget failed with error: %d\n", errno);
?? ??? ?exit(EXIT_FAILURE);
?? ?}
?? ?//從隊列中獲取消息,直到遇到end消息為止
?? ?while(running)
?? ?{
?? ??? ?if(msgrcv(msgid, (void*)&data, BUFSIZ, msgtype, 0) == -1)
?? ??? ?{
?? ??? ??? ?fprintf(stderr, "msgrcv failed with errno: %d\n", errno);
?? ??? ??? ?exit(EXIT_FAILURE);
?? ??? ?}
?? ??? ?printf("You wrote: %s\n",data.text);
?? ??? ?//遇到end結束
?? ??? ?if(strncmp(data.text, "end", 3) == 0)
?? ??? ??? ?running = 0;
?? ?}
?? ?//刪除消息隊列
?? ?if(msgctl(msgid, IPC_RMID, 0) == -1)
?? ?{
?? ??? ?fprintf(stderr, "msgctl(IPC_RMID) failed\n");
?? ??? ?exit(EXIT_FAILURE);
?? ?}
?? ?exit(EXIT_SUCCESS);
}
?
?
?
客戶端:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <errno.h>
?
#define MAX_TEXT 512
struct msg_st
{
?? ?long int msg_type;
?? ?char text[MAX_TEXT];
};
?
int main()
{
?? ?int running = 1;
?? ?struct msg_st data;
?? ?char buffer[BUFSIZ];
?? ?int msgid = -1;
?
?? ?//建立消息隊列
?? ?msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
?? ?if(msgid == -1)
?? ?{
?? ??? ?fprintf(stderr, "msgget failed with error: %d\n", errno);
?? ??? ?exit(EXIT_FAILURE);
?? ?}
?
?? ?//向消息隊列中寫消息,直到寫入end
?? ?while(running)
?? ?{
?? ??? ?//輸入數據
?? ??? ?printf("Enter some text: ");
?? ??? ?fgets(buffer, BUFSIZ, stdin);
?? ??? ?data.msg_type = 1; ? ?//注意2
?? ??? ?strcpy(data.text, buffer);
?? ??? ?//向隊列發送數據
?? ??? ?if(msgsnd(msgid, (void*)&data, MAX_TEXT, 0) == -1)
?? ??? ?{
?? ??? ??? ?fprintf(stderr, "msgsnd failed\n");
?? ??? ??? ?exit(EXIT_FAILURE);
?? ??? ?}
?? ??? ?//輸入end結束輸入
?? ??? ?if(strncmp(buffer, "end", 3) == 0)
?? ??? ??? ?running = 0;
?? ??? ?sleep(1);
?? ?}
?? ?exit(EXIT_SUCCESS);
}
?
總結
以上是生活随笔為你收集整理的linux C 应用消息队列在两个进程间通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 公共情报工具automater的基本使用
- 下一篇: 17. OD-带有多态、变形的程序进行打