创建管道
#include<myhead.h>
int main(int argc, const char *argv[])
{
//管道1
if(mkfifo("./myfifo",0664) !=0)
{
perror("ggg");
return -1;
}
printf("success 1\n");
//管道2
if(mkfifo("./my2fifo",0664) !=0)
{
perror("gggg");
return -1;
}
printf("success 2\n");
getchar();
system("rm myfifo");
system("rm my2fifo");
return 0;
}
进程a
#include<myhead.h>
int main(int argc, const char *argv[])
{
//写操作
int wid,wid2=-1;
pid_t pid;
pid=fork();
if(pid ==0)
{
if((wid=open("./myfifo",O_WRONLY)) ==-1)
{
perror("gggg");
return -1;
}
printf("写打开\n");
char wbuf[128]="";
while(1)
{
bzero(wbuf,sizeof(wbuf));
wbuf[strlen(wbuf)-1]='\0';
read(0,wbuf,sizeof(wbuf));
write(wid,wbuf,sizeof(wbuf));
printf("写入: %s",wbuf);
fflush(stdout);
if(strcmp(wbuf,"quit") ==0)
{
break;
}
}
close(wid);
exit(EXIT_SUCCESS);
}
else if(pid>0)
{
//读操作
if((wid2=open("./my2fifo",O_RDONLY)) ==-1)
{
perror("gggg");
return -1;
}
printf("读2打开\n");
char wbuf2[128]="";
while(1)
{
bzero(wbuf2,sizeof(wbuf2));
read(wid2,wbuf2,sizeof(wbuf2));
printf("收到: %s\n",wbuf2);
if(strcmp(wbuf2,"quit2") ==0)
{
break;
}
}
close(wid2);
}
else
{
perror("ggg");
return -1;
}
wait(NULL);
return 0;
}
进程b
#include<myhead.h>
int main(int argc, const char *argv[])
{
int rid,rid2=-1;
pid_t pid;
pid=fork();
if(pid ==0)
{
//读操作
if((rid=open("./myfifo",O_RDONLY)) ==-1)
{
perror("gggg");
return -1;
}
printf("读打开\n");
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
read(rid,rbuf,sizeof(rbuf));
printf("收到: %s\n",rbuf);
if(strcmp(rbuf,"quit") ==0)
{
break;
}
}
close(rid);
exit(EXIT_SUCCESS);
}
else if(pid>0)
{
//写操作
if((rid2=open("./my2fifo",O_WRONLY)) ==-1)
{
perror("gggg");
return -1;
}
printf("写2打开\n");
char rbuf2[128]="";
while(1)
{
bzero(rbuf2,sizeof(rbuf2));
rbuf2[strlen(rbuf2)-1]='\0';
read(0,rbuf2,sizeof(rbuf2));
write(rid2,rbuf2,sizeof(rbuf2));
printf("写入: %s",rbuf2);
fflush(stdout);
if(strcmp(rbuf2,"quit2") ==0)
{
break;
}
}
close(rid2);
}
else
{
perror("ggg");
return -1;
}
wait(NULL);
return 0;
}