1>使用消息队列完成两个进程之间相互通信
process1.c
#include<myhead.h>
//消息类型结构体
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE sizeof(struct msgbuf)-sizeof(long)
int main(int argc, const char *argv[])
{
//创建进程
pid_t pid=-1;
pid=fork();
if(pid<0)
{
printf("fork error");
return -1;
}
else if(pid==0) //子进程接收
{
//创建key
key_t key1 = ftok("/", 't');
if(key1 == -1)
{
perror("ftok error");
return -1;
}
// printf("key = %#x\n", key);
//创建消息队列
int msqid = msgget(key1, IPC_CREAT|0664);
if(msqid == -1)
{
perror("msgget error");
return -1;
}
// printf("msqid = %d\n", msqid); //id号
//从消息队列中读取消息
struct msgbuf buf1;
while(1)
{
msgrcv(msqid, &buf1, SIZE, 0, 0);
printf("收到消息为:%s\n", buf1.mtext);
if(strcmp(buf1.mtext, "quit") == 0)
{
break;
}
}
//删除消息队列
if(msgctl(msqid, IPC_RMID, NULL) ==-1)
{
perror("msgctl error");
return -1;
}
exit(EXIT_SUCCESS);
}
//父进程发送
//创建key
key_t key = ftok("/", 'k');
if(key == -1)
{
perror("ftok error");
return -1;
}
// printf("key = %#x\n", key);
//创建消息队列
int msqid = msgget(key, IPC_CREAT|0664);
if(msqid == -1)
{
perror("msgget error");
return -1;
}
// printf("msqid = %d\n", msqid); //id号
//向消息队列中存放消息
struct msgbuf buf;
while(1)
{
printf("请输入消息类型:");
scanf("%ld", &buf.mtype);
getchar(); //吸收回车
printf("请输入消息正文:");
fgets(buf.mtext, SIZE, stdin); //从终端获取数据
buf.mtext[strlen(buf.mtext)-1] = 0; //将换行换成 '\0'
//将消息发送到消息队列中
msgsnd(msqid, &buf, SIZE, 0);
printf("发送成功\n");
if(strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
wait(NULL);
return 0;
}
process2.c
#include<myhead.h>
//消息类型结构体
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE sizeof(struct msgbuf)-sizeof(long)
int main(int argc, const char *argv[])
{
//创建进程
pid_t pid=-1;
pid=fork();
if(pid<0)
{
printf("fork error");
return -1;
}
else if(pid==0) //子进程发送
{
//创建key
key_t key1 = ftok("/", 't');
if(key1 == -1)
{
perror("ftok error");
return -1;
}
// printf("key = %#x\n", key);
//创建消息队列
int msqid = msgget(key1, IPC_CREAT|0664);
if(msqid == -1)
{
perror("msgget error");
return -1;
}
// printf("msqid = %d\n", msqid); //id号
//向消息队列中存放消息
struct msgbuf buf1;
while(1)
{
printf("请输入消息类型:");
scanf("%ld", &buf1.mtype);
getchar(); //吸收回车
printf("请输入消息正文:");
fgets(buf1.mtext, SIZE, stdin); //从终端获取数据
buf1.mtext[strlen(buf1.mtext)-1] = 0; //将换行换成 '\0'
//将消息发送到消息队列中
msgsnd(msqid, &buf1, SIZE, 0);
printf("发送成功\n");
if(strcmp(buf1.mtext, "quit") == 0)
{
break;
}
}
exit(EXIT_SUCCESS);
}
//父进程接收
//创建key
key_t key = ftok("/", 'k');
if(key == -1)
{
perror("ftok error");
return -1;
}
// printf("key = %#x\n", key);
//创建消息队列
int msqid = msgget(key, IPC_CREAT|0664);
if(msqid == -1)
{
perror("msgget error");
return -1;
}
// printf("msqid = %d\n", msqid); //id号
//从消息队列中读取消息
struct msgbuf buf;
while(1)
{
msgrcv(msqid, &buf, SIZE, 0, 0);
printf("收到消息为:%s\n", buf.mtext);
if(strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
//删除消息队列
if(msgctl(msqid, IPC_RMID, NULL) ==-1)
{
perror("msgctl error");
return -1;
}
wait(NULL);
return 0;
}
思维导图