利用管道,双向通信
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char *argv[])
{
if(mkfifo("./mypipe",0664))
{
perror("wrong");
return -1;
}
if(mkfifo("./yourpipe",0664))
{
perror("wrong");
return -1;
}
getchar();
system("./mypipe");
system("./yourpipe");
return 0;
}
2.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc,char *argv[])
{
pid_t vvv=fork();
if(vvv<0)
{
perror("Wrong");
exit(-1);
}
else if(vvv==0)
{
int myr=open("./mypipe",O_WRONLY);
char buf[128];
if(myr<0)
{
perror("Wrong");
exit(-1);
}
while(1)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(myr,buf,strlen(buf));
if(strcmp(buf,"over"))
break;
}
close(myr);
exit(0);
}
else
{
int yourr=open("./yourpipe",O_RDONLY);
char buf[128];
if(yourr<0)
{
perror("Wrong");
exit(-1);
}
while(1)
{
bzero(buf,sizeof(buf));
read(yourr,buf,strlen(buf));
if(strcmp(buf,"over")==0)
break;
printf("%s\n",buf);
}
close(yourr);
wait(NULL);
}
return 0;
}
3.c
int main(int argc,char *argv[])
{
pid_t vvv=fork();
if(vvv<0)
{
perror("Wrong");
exit(-1);
}
else if(vvv=0)
{
char buf[128];
int myr=open("./mypipe",O_WRONLY);
if(myr<0)
{
perror("Wrong");
exit(-1);
}
while(1)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(myr,buf,strlen(buf));
if(strcmp(buf,"over"))
break;
}
close(myr);
exit(0);
}
else
{
char buf[128];
int yourr=open("./yourpipe",O_RDONLY);
if(yourr<0)
{
perror("Wrong");
exit(-1);
}
while(1)
{
bzero(buf,sizeof(buf));
read(yourr,buf,strlen(buf));
if(strcmp(buf,"over")==0)
break;
printf("%s\n",buf);
}
close(yourr);
wait(NULL);
}
return 0;
}