使用多进程完成管道全双工通信
#include <myhead.h>
//寫入線程
void *task1(void *arg)
{
//定義文件描述符
int fd1;
//打開管道文件
if((fd1=open("./myfifo1",O_WRONLY))==-1)
{
perror("open error");
return NULL;
}
while(1)
{
//定義容器
char str[128]="";
//獲取數據
fgets(str,sizeof(str),stdin);
//把\n置爲\0
str[strlen(str)-1]='\0';
//將數據寫入管道
write(fd1,str,strlen(str));
printf("發送的數據爲:%s\n",str);
if(strcmp(str,"quit")==0)
{
break;
}
}
//關閉管道
close(fd1);
pthread_exit(NULL);
}
void *task2(void *arg)
{
//定義文件描述符
int fd2;
//打開管道文件
if((fd2=open("./myfifo2",O_RDONLY))==-1)
{
perror("open error");
return NULL;
}
printf("asdds");
while(1)
{
//定義容器
char str[128]="";
//讀取數據
read(fd2,str,sizeof(str));
printf("接收的數據爲: %s\n",str);
if(strcmp(str,"quit")==0)
{
break;
}
}
//關閉管道
close(fd2);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//定義線程號
pthread_t tid1,tid2;
//創建線程
if(pthread_create(&tid1,NULL,task1,NULL))
{
perror("create tid1 error");
return -1;;
}
//創建線程
if(pthread_create(&tid2,NULL,task2,NULL))
{
perror("create tid2 error");
return -1;
}
//初始化信號量
//sem_init(&sem,0,0);
///回收線程資源
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
#include <myhead.h>
//寫入線程
void *task1(void *arg)
{
//定義文件描述符
int fd;
//打開管道文件
if((fd=open("./myfifo2",O_WRONLY))==-1)
{
perror("open error");
return NULL;
}
while(1)
{
//定義容器
char str[128]="";
//獲取數據
fgets(str,sizeof(str),stdin);
//把\n置爲\0
str[strlen(str)-1]='\0';
//將數據寫入管道
write(fd,str,strlen(str));
printf("發送的數據爲:%s\n",str);
if(strcmp(str,"quit")==0)
{
break;
}
}
//關閉管道
close(fd);
pthread_exit(NULL);
}
void *task2(void *arg)
{
//定義文件描述符
int fd;
//打開管道文件
if((fd=open("./myfifo1",O_RDONLY))==-1)
{
perror("open error");
return NULL;
}
while(1)
{
//定義容器
char str[128]="";
//讀取數據
read(fd,str,sizeof(str));
printf("接收的數據爲: %s\n",str);
if(strcmp(str,"quit")==0)
{
break;
}
}
//關閉管道
close(fd);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//定義線程號
pthread_t tid1,tid2;
//創建線程
if(pthread_create(&tid1,NULL,task1,NULL))
{
perror("create tid1 error");
return -1;;
}
//創建線程
if(pthread_create(&tid2,NULL,task2,NULL))
{
perror("create tid2 error");
return -1;;
}
//回收線程資源
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
#include <myhead.h>
int main(int argc, const char *argv[])
{
//創建管道文件
if(mkfifo("./myfifo1",0664)==-1)
{
perror("mkfifo1 error");
return -1;
}
//創建管道文件
if(mkfifo("./myfifo2",0664)==-1)
{
perror("mkfifo2 error");
return -1;
}
//使用函數阻塞主函數
getchar();
//刪除管道文件
system("rm myfifo1");
system("rm myfifo2");
return 0;
}