我在网上想找多进程之间的通信方式,发现有人写的消息队列很好,搬过来:
common.h
#ifndef __COMMON_H_
#define __COMMON_H_ #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <string.h>
#include <time.h> #define MSG_SIZE 1024
#define FILEPATH "."
#define ID 0
#define SERVER_TYPE 1
#define CLIENT_TYPE 2 typedef struct msg_info {
long mtype;
char mtext[MSG_SIZE];
}msginfo; int CreateMessageQueue();
int GetMessageQueue();
int DeleteMessageQueue(int msgid);
int SendDataToMessageQueue(int msg_id, int send_type, char *msg);
int ReceiveDataFromMessageQueue(int msg_id, int receive_type, char *out); #endif
common.c
#include "common.h" static int CommonMessageQueue(int flags)
{
key_t _key = ftok(FILEPATH, ID);
if(_key == -) {
perror("ftok error");
return ;
}
int _msg_id = msgget(_key, flags);
if(_msg_id < ) {
perror("msgget error");
return ;
}
return _msg_id;
} int CreateMessageQueue()
{
return CommonMessageQueue(IPC_CREAT|IPC_EXCL|);
} int GetMessageQueue()
{
return CommonMessageQueue(IPC_CREAT);
} int DeleteMessageQueue(int msg_id)
{
if(msgctl(msg_id, IPC_RMID, NULL) < )
return -;
return ;
} int SendDataToMessageQueue(int msg_id, int send_type, char *msg)
{
msginfo buff;
buff.mtype = send_type;
strcpy(buff.mtext, msg);
int msg_snd = msgsnd(msg_id, (void *)&buff, sizeof(buff), );
if(msg_snd < ) {
perror("msgsnd error");
return -;
}
return ;
} int ReceiveDataFromMessageQueue(int msg_id, int receive_type, char *out)
{
msginfo buff;
int msg_rcv = msgrcv(msg_id, (void *)&buff, sizeof(buff), receive_type, );
if(msg_rcv < ) {
perror("msg_rcv error");
return -;
}
strcpy(out, buff.mtext);
return ;
}
server.c
#include "common.h" int main()
{
char buff[MSG_SIZE];
int msg_id = CreateMessageQueue(); while()
{
//send data
printf("server please enter# ");
fflush(stdout);
ssize_t s = read(, buff, sizeof(buff)-);
if(s > ) {
buff[s-] = ;
SendDataToMessageQueue(msg_id, SERVER_TYPE, buff);
printf("data has sended,wait receive......\n");
} else {
perror("read error");
return ;
} //receive data
ReceiveDataFromMessageQueue(msg_id, CLIENT_TYPE, buff);
printf("from client: %s\n", buff);
}
DeleteMessageQueue(msg_id); return ;
}
client:
#include "common.h" int main()
{
char buff[MSG_SIZE];
int msg_id = GetMessageQueue();
while() {
//receive data
ReceiveDataFromMessageQueue(msg_id, SERVER_TYPE, buff);
printf("from server:%s\n", buff); //send data
printf("client please enter# ");
fflush(stdout);
ssize_t s = read(, buff, sizeof(buff)-);
if(s <= ) {
perror("read error");
return ;
} else {
buff[s-] = ;
SendDataToMessageQueue(msg_id, CLIENT_TYPE, buff);
printf("data has sended,wait receive......\n");
}
}
return ;
}
Makefile:
all:client server client: common.c client.c
gcc -o $@ $^
server: common.c server.c
gcc -o $@ $^ .PHONY:clean
clean:
rm -rf client server