1> 使用有名管道实现,一个进程用于给另一个进程发消息,另一个进程收到消息后,展示到终端上,并且将消息保存到文件上一份
create.c
#include <myhead.h>
int main(int argc,const char *argv[])
{
if(mkfifo("./linux",0644)==-1)
{
perror("mkfifo error");
return -1;
}
getchar();
system("rm linux");
return 0;
}
snd.c
#include <myhead.h>
int main(int argc,const char *argv[])
{
int wfd = open("./linux",O_WRONLY);
if(wfd==-1)
{
perror("open error");
return -1;
}
char wbuf[128]="";
while(1)
{
printf("请输入>>>");
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)-1]=0;
write(wfd,wbuf,strlen(wbuf));
if(strcmp(wbuf,"quit")==0)
{
break;
}
}
close(wfd);
return 0;
}
recv.c
#include <myhead.h>
int main(int argc,const char *argv[])
{
int rfd = open("./linux",O_RDONLY);
if(rfd==-1)
{
perror("open error");
return -1;
}
int fd = open("./test.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fd==-1)
{
perror("open error");
return -1;
}
char rbuf[128]="";
while(1)
{
memset(rbuf,0,sizeof(rbuf));
read(rfd,rbuf,sizeof(rbuf));
if(strcmp(rbuf,"quit")==0)
{
break;
}
printf("收到的信息为:%s\n",rbuf);
write(fd,rbuf,strlen(rbuf));
}
close(rfd);
close(fd);
return 0;
}
2> 使用有名管道实现两个进程间相互通信
create.c
#include <myhead.h>
int main(int argc,const char *argv[])
{
if(mkfifo("./linux1",0644)==-1)
{
perror("mkfifo perror");
return -1;
}
if(mkfifo("./linux2",0644)==-1)
{
perror("mkfifo perror");
return -1;
}
getchar();
system("rm linux1");
system("rm linux2");
return 0;
}
1.c
#include <myhead.h>
int main(int argc,const char *argv[])
{
pid_t pid = fork();
if(pid<0)
{
perror("fork error");
return -1;
}
else if(pid==0)
{
int rfd=-1;
if((rfd=open("./linux2",O_RDONLY))==-1)
{
perror("open error");
return -1;
}
char rbuf[128]="";
while(1)
{
memset(rbuf,0,sizeof(rbuf));
read(rfd,rbuf,sizeof(rbuf));
if(strcmp(rbuf,"quit")==0)
{
break;
}
printf("收到的信息为:%s\n",rbuf);
}
close(rfd);
exit(EXIT_SUCCESS);
}
int wfd=-1;
if((wfd=open("./linux1",O_WRONLY))==-1)
{
perror("open error");
return -1;
}
char wbuf[128]="";
while(1)
{
printf("请输入>>>");
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)-1]=0;
write(wfd,wbuf,strlen(wbuf));
if(strcmp(wbuf,"quit")==0)
{
break;
}
}
close(wfd);
wait(NULL);
return 0;
}
2.c
#include <myhead.h>
int main(int argc,const char *argv[])
{
pid_t pid = fork();
if(pid<0)
{
perror("fork error");
return -1;
}
else if(pid==0)
{
int wfd=-1;
if((wfd=open("./linux2",O_WRONLY))==-1)
{
perror("open error");
return -1;
}
char wbuf[128]="";
while(1)
{
printf("请输入>>>");
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)-1]=0;
write(wfd,wbuf,strlen(wbuf));
if(strcmp(wbuf,"quit")==0)
{
break;
}
}
close(wfd);
exit(EXIT_SUCCESS);
}
int rfd=-1;
if((rfd=open("./linux1",O_RDONLY))==-1)
{
perror("open error");
return -1;
}
char rbuf[128]="";
while(1)
{
memset(rbuf,0,sizeof(rbuf));
read(rfd,rbuf,sizeof(rbuf));
if(strcmp(rbuf,"quit")==0)
{
break;
}
printf("收到的信息为:%s\n",rbuf);
}
close(rfd);
wait(NULL);
return 0;
}
思维导图