1)要求AB进程做通信
1. A进程发送一句话,B进程接收打印
2. 然后B进程发送给A进程一句话,A进程接收打印
3. 重复1,2步骤,直到A进程或者B进程收到quit,退出AB进程;
2)在第一题的基础上实现,AB进程能够随时收发数据(附加题)
A进程的内容
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include<pthread.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
int msqid;
int msqid2;
//A进程
//消息包结构体
struct msgbuf
{
long mtype; //消息类型
char mtext[128]; //消息内容
};
void *callback(void* arg)
{
struct msgbuf rcv;
while(1)
{ struct msgbuf rcv;
int res=msgrcv(msqid2,&rcv,sizeof(rcv.mtext),0,0);
printf("\n接收到的消息:%ld : %s\n",res,rcv.mtext);
// printf("请输入要发送的信息>>>");
if(strcmp(rcv.mtext,"quit") == 0)
{
exit(0);
}
}
// pthread_exit((void*)1);
}
int main(int argc, const char *argv[])
{
//计算key1值
key_t key =ftok("./",1);
printf("key =%#x\n",key);
//创建一个消息队列
msqid = msgget(key,IPC_CREAT|0777);
//计算key2的值
key_t key2=ftok("./",2);
printf("key2=%#x\n",key2);
msqid2 = msgget(key2,IPC_CREAT|0777);
//创建一个线程
pthread_t tid;
pthread_create(&tid,NULL,callback,NULL);
//发送消息包
struct msgbuf snd;
// printf("请输入消息类型>>>");
// scanf("%ld",&snd.mtype);
// getchar();
snd.mtype=1;
printf("请输入发送的消息>>>");
while(1)
{
//printf("请输入要发送的内容:>>>");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1]=0;
msgsnd(msqid,&snd,sizeof(snd.mtext),0);
if(strcmp(snd.mtext,"quit") == 0)
{
// pthread_cancel(tid);
//break;
exit(0);
}
}
pthread_join(tid,NULL);
return 0;
}
B进程的代码段内容
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/ipc.h>
#include<sys/msg.h>
int msqid;
int msqid2;
//B进程
//消息包结构体
struct msgbuf
{
long mtype; //消息类型
char mtext[128]; //消息内容
};
void *fuckback(void* arg)
{
struct msgbuf rcv;
while(1)
{
int res=msgrcv(msqid,&rcv,sizeof(rcv.mtext),0,0);
printf("\n接收到的消息:%ld : %s\n",res,rcv.mtext);
// printf("请输入要发送的信息>>>");
if(strcmp(rcv.mtext,"quit") == 0)
{
// pthread_cancel()
exit(0);
}
}
// pthread_exit((void*)1);
}
int main(int argc, const char *argv[])
{
//计算key1值
key_t key =ftok("./",1);
printf("key =%#x\n",key);
//创建一个消息队列
msqid = msgget(key,IPC_CREAT|0777);
//计算key2的值
key_t key2=ftok("./",2);
printf("key2=%#x\n",key2);
msqid2 = msgget(key2,IPC_CREAT|0777);
//创建一个线程
pthread_t pid;
pthread_create(&pid,NULL,fuckback,NULL);
//发送消息包
struct msgbuf snd;
// printf("请输入消息类型>>>");
// scanf("%ld",&snd.mtype);
// getchar();
snd.mtype=1;
printf("请输入发送的消息>>>");
while(1)
{
// printf("请输入要发送的内容:>>>");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1]=0;
msgsnd(msqid2,&snd,sizeof(snd.mtext),0);
if(strcmp(snd.mtext,"quit") == 0)
{
//break;
exit(0);
}
}
pthread_join(pid,NULL);
return 0;
}