1. 使用消息队列完成两个进程之间相互通信
代码
#include <myhead.h>
//define a msg struct type
struct msgbuf
{
long mtype; //消息类型
char mtext[1024]; //消息正文大小
};
//macro msg size
#define SIZE (sizeof(struct msgbuf)-sizeof(long))
int recv(int mtype_recv)
{
//*-----snd-----
//1. create key
key_t key = ftok("/", 'k');
if(key==-1)
{
perror("error");
return -1;
}
printf("key=%#x\n", key);
//2. create msg queue
int msgid = msgget(key, IPC_CREAT | 0664);
if(msgid == -1)
{
perror("msgget error");
return -1;
}
printf("msgid=%d\n", msgid);
//3. send msg to msg queue
//define a msg var
struct msgbuf buf;
while(1)
{
//将消息从消息队列读取
msgrcv(msgid, &buf, SIZE, mtype_recv, 0 );
//param1: msg queue id
//param2; buffer start address
//param3: msg text size
//param4: msg type
//param5: if block, 0--> block;
printf("recv msg=%s\n", buf.mtext);
//
if(strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
//4. delete msg queue
if ((msgctl(msgid, IPC_RMID, NULL)) == -1)
{
perror("msgctl error");
return -1;
}
}
void* task_recv(void* arg)
{
int *pmtype_recv = (int *)arg;
recv(*pmtype_recv);
}
int main(int argc, const char *argv[])
{
int mtype_snd = 0;
int mtype_recv = 0;
printf("plesae input msg type for sender:\n>");
scanf("%d", &mtype_snd );
printf("plesae input msg type for receiver:\n>");
scanf("%d", &mtype_recv );
int *pmtype_recv = &mtype_recv;
pthread_t tid = -1;
int res = pthread_create(&tid, NULL, task_recv, (void *)pmtype_recv );
if(res !=0 )
{
printf("thread create error\n");
return -1;
}
//*-----snd-----
//1. create key
key_t key = ftok("/", 'k');
if(key==-1)
{
perror("error");
return -1;
}
printf("key=%#x\n", key);
//2. create msg queue
int msgid = msgget(key, IPC_CREAT | 0664);
if(msgid == -1)
{
perror("msgget error");
return -1;
}
printf("msgid=%d\n", msgid);
//3. send msg to msg queue
//define a msg var
struct msgbuf buf;
buf.mtype = mtype_snd;
while(1)
{
printf("please input msg to send:");
scanf("%s", buf.mtext);
//将消息从消息队列读取
msgsnd(msgid, &buf, SIZE, 0 );
//param1: msg queue id
//param2; buffer start address
//param3: msg text
//param4: if block, 0--> block;
printf("recv msg=%s\n", buf.mtext);
//
if(strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
//4. delete msg queue
if ((msgctl(msgid, IPC_RMID, NULL)) == -1)
{
perror("msgctl error");
return -1;
}
return 0;
}
运行结果