UNIX环境高级编程学习之第十五章进程间通信 – 通过消息队列实现进程间通信
[code lang=”cpp”]/* User:Lixiujie
* Date:20100825
* Desc:通过消息队列实现进程间通信
* File:MsgQueue.c
* gcc MsgQueue.c -o MsgQueue1
* 把SEND_TYPE修改为2 RECV_TYPE修改为1
* gcc MsgQueue.c -o MsgQueue2
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>

#define SEND_TYPE 1
#define RECV_TYPE 2

typedef struct MsgBuf{
long lType;
char szData[512];
}Msg;

/* 取当前文件路径 */
char* getCurrentFilePath(char *szCurrentFilePath){
char szBuf[256] = { 0x00 };
strcpy(szBuf, __FILE__);
if (strstr(szBuf, "/") == NULL){
memset(szBuf, 0x00, sizeof(szBuf));
strcpy(szBuf, getenv("PWD"));
strcat(szBuf, "/");
strcat(szBuf, __FILE__);
}
strcpy(szCurrentFilePath, szBuf);
return szCurrentFilePath;
}

/* 发送信息线程 */
void *SendMsgThread(void *pData){
int mqID = *(int*)pData;
int ret;
while (1){
Msg msg;
memset(&msg, 0x00, sizeof(msg));
msg.lType = SEND_TYPE;
sprintf(msg.szData, "%ul:Hello world!/n", getpid());
ret = msgsnd(mqID, &msg, sizeof(msg.szData), IPC_NOWAIT);
if (-1 == ret){
perror("SendMsgThread() msgsnd() is failed!/n");
}
sleep(3);
}
return (void*)0;
}

/* 接收信息线程 */
void *RecvMsgThread(void *pData){
int mqID = *(int*)pData;
int ret;
while (1){
Msg msg;
memset(&msg, 0x00, sizeof(msg));
msg.lType = RECV_TYPE;
ret = msgrcv(mqID, (void*)&msg, sizeof(msg.szData), msg.1Type, 0);
if (-1 == ret){
perror("RecvMsgThread() msgrcv() is failed!/n");
}
printf("PID=%ul RECV DATA:%s/n",getpid(), msg.szData);
}
return (void*)0;
}
int main(int argc, char *argv[])
{
int ret;
key_t mqKey;
char szCurrentFilePath[256] = { 0x00 };
getCurrentFilePath(szCurrentFilePath);
/* 产生key */
mqKey = ftok(szCurrentFilePath, 1);
if (-1 == mqKey){
perror("main() ftok() is failed!/n");
exit(1);
}
/* 定义消息队列ID */
int mqID;
/* 产生或获取消息队列 */
mqID = msgget(mqKey, IPC_CREAT|0666);
if (-1 == mqID){
perror("main() msgget() is failed!/n");
exit(1);
}
pthread_t pth[2];
ret = pthread_create(&pth[0], NULL, SendMsgThread, &mqID);
if (ret != 0){
perror("main() pthread_create() is failed!/n");
exit(1);
}
ret = pthread_create(&pth[1], NULL, RecvMsgThread, &mqID);
if (ret != 0){
perror("main() pthread_create() is failed!/n");
exit(1);
}
pthread_detach(pth[0]);
pthread_detach(pth[1]);
while (1){
char szCMD[64] = { 0x00 };
gets(szCMD);
if (strcmp(szCMD, "quit") == 0){
exit(1);
}else if (strcmp(szCMD, "exit") == 0){
exit(1);
}
sleep(1);
}
return 0;
}
/* 删除消息队列 */
int rmMQ(int mqID){
reutnr msgctl(mqID, IPC_RMID, NULL);
}

[/code]

发表评论