1.思维导图
2.通过管道实现两个线程间的相互通信
第一个管道程序 create.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<time.h>
#include<sys/wait.h>
#include<pthread.h>
#include<semaphore.h>
int main(int argc, const char *argv[])
{
//创建管道文件
if(mkfifo("./myfifo", 0664))
{
perror("mkfifo error");
return -1;
}
//阻塞等待其他进程使用管道
getchar();
//用过代码执行终端指令
system("rm myfifo");
return 0;
}
第二个管道程序 create2.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<time.h>
#include<sys/wait.h>
#include<pthread.h>
#include<semaphore.h>
int main(int argc, const char *argv[])
{
//创建管道文件
if(mkfifo("./myfifo2", 0664))
{
perror("mkfifo2 error");
return -1;
}
//阻塞等待其他进程使用管道
getchar();
//用过代码执行终端指令
system("rm myfifo2");
return 0;
}
write.c程序
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<time.h>
#include<sys/wait.h>
#include<pthread.h>
#include<semaphore.h>
int main(int argc, const char *argv[])
{
int fd,fdr; //文件描述符
char buf[128] ="";//写文件数组
char bufr[128]="";//管道2读文件数组
//打开有名管道文件1
if((fd = open("./myfifo", O_WRONLY)) == -1)
{
perror("open error");
return -1;
}
//打开有名管道文件2
if((fdr=open("./myfifo2",O_RDONLY))==-1)
{
perror("open 2error");
return -1;
}
while(1)
{
//1.循环往管道1中写数据
printf("小明(我):");
fgets(buf, sizeof(buf), stdin);
//清掉'\n'
buf[strlen(buf) - 1] = '\0';
//将输入写入管道中
write(fd, buf, strlen(buf));
//如果输入的是quit
if(strcmp(buf, "quit") == 0)
{
break;
}
//2.循环往管道2中读数据
memset(bufr,0,sizeof(bufr));
read(fdr,bufr,sizeof(bufr) );
if(strcmp(bufr,"end")==0)
{
break;
}
printf("小华说:%s\n",bufr);
}
//关闭文件
close(fd);
close(fdr);
return 0;
}
read.c程序
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<time.h>
#include<sys/wait.h>
#include<pthread.h>
#include<semaphore.h>
int main(int argc, const char *argv[])
{
//定义文件描述符
int fd,fdw;
char buf[128] = "";//管道1读文件数组
char bufw[128]=""; //管道2写文件数组
//打开管道文件1
if((fd = open("./myfifo", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
//打开管道文件2
if((fdw=open("./myfifo2",O_WRONLY))==-1)
{
perror("open 2error");
return -1;
}
while(1)
{
memset(buf, 0, sizeof(buf));
//1.从管道1中读取数据
read(fd, buf, sizeof(buf));
if(strcmp(buf, "quit") == 0)
{
break;
}
printf("小明说:%s\n", buf); //将内容打印在终端上
//2.向管道2中写数据
printf("小华(我):");
fgets(bufw,sizeof(bufw),stdin);
bufw[strlen(bufw)-1]='\0';
//输入写到管道2中
write(fdw,bufw,sizeof(bufw));
if(strcmp(bufw,"end")==0)
{
break;
}
}
close(fd); //关闭文件
close(fdw);
return 0;
}
实现效果