Linux下进程之间通过消息队列通信小程序示例
2014-12-01 11:57
531 查看
/*commom.h*/ #include <sys/types.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/msg.h> #include <string.h> #include <malloc.h> #define SIZE 512 #define MAXSENDSIZE (sizeof(Message)-sizeof(long int)) typedef struct { long int type; int val; char buffer[SIZE]; }Message; int alloc_msg(Message **msg)/*注意要用双重指针来传递动态内存*/ { *msg = (Message *)malloc(sizeof(Message)); if (NULL == *msg) { perror("alloc_msg failed!\n"); exit(1); } memset(*msg, 0, sizeof(Message)); return 0; } int free_msg(Message **msg)/*注意要用双重指针来释放动态内存*/ { free(*msg); return 0; } int create_msg(key_t key) { int msgid; msgid = msgget(key, 0666|IPC_CREAT); if (msgid == -1) { perror("create_msg failed!\n"); exit(1); } return msgid; } int send_msg(int msgid, Message *msg) { if (msgsnd(msgid, (void*)msg, MAXSENDSIZE, 0)==-1) { perror("send_msg failed!\n"); exit(1); } return 0; } int rev_msg(int msgid, Message *msg,long int type) { if (msgrcv(msgid, (void *)msg, MAXSENDSIZE, type, 0)==-1) { perror("msg_rev failed!\n"); exit(1); } return 0; } int del_msg(int msgid) { if (msgctl(msgid, IPC_RMID, NULL)==-1) { perror("msg_del failed!\n"); exit(1); } return 0; }
/*send.c*/ #include <stdio.h> #include <stdlib.h> #include "commom.h" int main(void) { int msgid; key_t key; Message *msg = NULL; alloc_msg(&msg); key = ftok("./commom.h", 0); msgid = create_msg(key); msg->type = 1; msg->val = 10; strncpy(msg->buffer, "hello world", SIZE); send_msg(msgid, msg); msg->type = 2; msg->val = 12; strncpy(msg->buffer, "english test", SIZE); send_msg(msgid, msg); free_msg(&msg); return 0; }
/*receive.c*/ #include <stdio.h> #include <stdlib.h> #include "commom.h" int main(void) { int msgid; key_t key; Message *msg = NULL; alloc_msg(&msg); long int type1 = 1; long int type2 = 2; key = ftok("./commom.h", 0); msgid = create_msg(key); rev_msg(msgid, msg, type1); printf("rev_message is:type = %ld; %s, val = %d\n", msg->type, msg->buffer, msg->val); rev_msg(msgid, msg, type2); printf("rev_message is:type = %ld; %s, val = %d\n", msg->type, msg->buffer, msg->val); del_msg(msgid); free_msg(&msg); return 0; }
#makefile CFLAGS = -Wall -g CC = gcc TARGET1 = send TARGET2 = receive all:$(TARGET1) $(TARGET2) $(TARGET1):$(TARGET1).o $(CC) $(CFLAGS) -o $@ $^ $(TARGET2):$(TARGET2).o $(CC) $(CFLAGS) -o $@ $^ %.o:%.c $(CC) -c $(CFLAGS) -o $@ $< clean: rm -f *.o $(TARGET1) $(TARGET2)
先发送后接收
相关文章推荐
- Linux进程之间通信消息队列
- 进程通信程序整理---消息队列(Linux)
- Linux C程序练习(3)进程通信之pipe、fifo、消息队列
- linux基础编程:进程通信之System V IPC:消息队列,信号量,共享内存
- linux消息队列进程通信
- Linux下进程通信之消息队列
- [Linux] 进程通信-消息队列
- Linux进程通信 消息队列
- 通过共享内存,利用循环队列实现两个进程A,B之间的通信
- Linux进程通信之POSIX消息队列
- linux消息队列进程通信
- linux 环境下的进程间的通信——消息队列传输结构体
- linux消息队列进程通信
- linux 进程间间通信使用消息队列
- msgget();msgsnd();msgrcv();msgctl(); 消息队列 Linux进程间的通信方式之消息队列
- Linux消息队列进程通信的介绍
- linux消息队列进程通信
- 进程之间如何通过消息队列传输大量数据
- UNIX/LINUX编程学习之进程通信--消息队列
- 【linux高级环境编程学习笔记四】消息队列进程通信