第六题
三种通信方式
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<errno.h>
#include<sys/ipc.h>
#include<sys/shm.h>
using namespace std;
struct REQ
{
long int type;
char send[50];
};
const int SVKEY=75;
void hjpipe()
{
int fd[2];
int flag=pipe(fd);//创建管道
if(flag==-1) perror("pipe error");
pid_t pid=fork();//创建子进程
if(pid==0)//子进程 发送
{
close(fd[0]);
char writebuf[100];
int ppid=getpid();
sprintf(writebuf,"%d is sending a message to parent",ppid);
write(fd[1],writebuf,strlen(writebuf));
exit(0);
}
else if(pid>0)//父进程 读取后终止
{
close(fd[1]);
sleep(1);
char readbuf[100];
read(fd[0],readbuf,100);
printf("%s\n",readbuf);
}
else exit(0);
}
void hjmsgque()
{
pid_t pid1=1,pid2=1;
pid1=fork();
if(pid1==0) //hjserver();
{
int msgid=msgget(SVKEY,0777|IPC_CREAT);
struct REQ rcv,snd;
msgrcv(msgid,&rcv,sizeof(struct REQ)-sizeof(long),1,0);
printf("%s",rcv.send);
sscanf(rcv.send,"SERVER:serving for client pid of %ld\n",&snd.type);
sprintf(snd.send,"CLIENT:receive reply from %d\n",getpid());
msgsnd(msgid,&snd,sizeof(struct REQ)-sizeof(long),0);
kill(getpid(),SIGKILL);
}
else
{
pid2=fork();
if(pid2==0) //hjclient();
{
int msgid=msgget(SVKEY,0777);
pid_t pid=getpid();
struct REQ snd,rcv;
snd.type=1;
sprintf(snd.send,"SERVER:serving for client pid of %d\n",pid);
msgsnd(msgid,&snd,sizeof(struct REQ)-sizeof(long),0);
msgrcv(msgid,&rcv,sizeof(struct REQ)-sizeof(long),pid,0);
printf("%s",rcv.send);
kill(getpid(),SIGKILL);
}
//else wait(NULL);
}
wait(NULL);
}
void hjshared()
{
int shmid=shmget(SVKEY,512,IPC_CREAT|0777);
pid_t pid=fork();
if(pid==0)//子进程 写
{
char *addr=(char *)shmat(shmid,NULL,0);
sprintf(addr,"%d is sending a message to parent",getpid());
shmdt(addr);
exit(0);
}
else//父进程 读
{
char *addr=(char *)shmat(shmid,NULL,0);
sleep(1);
printf("%s\n",addr);
shmdt(addr);
shmctl(shmid,IPC_RMID,0);
}
}
int main()
{
char select;
while(1)
{
printf("\n******进程通信******\n");
printf("*****1.管道通信*****\n");
printf("*****2.缓冲队列*****\n");
printf("*****3.共享存储*****\n");
printf("*******0.退出*******\n");
printf("***请输入0~3的数字**\n");
//scanf("%c",&select);
cin>>select;
switch(select)
{
case '0':exit(0);break;
case '1':hjpipe();break;
case '2':hjmsgque();break;
case '3':hjshared();break;
default:printf("输入有误!\n");break;
}
sleep(1);
}
return 0;
}