作業
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
#include<unistd.h>
#include<errno.h>
#include<pthread.h>
pthread_t tid;
char arr[128]="";
ssize_t rad;
int fd,fd1;
void *zyy(void*p)
{
while(1)
{
bzero(arr,sizeof(arr));
printf("请输入\n");
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1]=0;
if(write(fd,arr,sizeof(arr))<0)
{
perror("write");
return NULL;
}
printf("写入数据成功\n");
}
}
int main(int argc, const char *argv[])
{
pthread_create(&tid,NULL,zyy,NULL);
//创建有名管道
if(mkfifo("./fifo",0667)<0)
{
if(errno!=17)
{
perror("mkfifo");//文件存在错误 这是一个允许存在的错误
return -1;
}
}
printf("管道1创建成功\n");
if(mkfifo("./fifo1",0667)<0)
{
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("管道2创建成功\n");
//有名方式打开管道文件 以只读的方式打开open函数阻塞
fd=open("./fifo",O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("管道打开成功\n");
fd1=open("./fifo1",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("管道1打开成功\n");
while(1)//读取数据
{
bzero(arr,sizeof(arr));
if((rad=read(fd1,arr,sizeof(arr)))<0)
{
perror("read");
return -1;
}
if(rad==0)
{
printf("写端关闭\n");
break;
}
if(strcmp(arr,"quit")==0)
{
break;
}
printf("%s\n",arr);
}
close(fd);
close(fd1);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<head.h>
#include<unistd.h>
#include<errno.h>
#include<pthread.h>
pthread_t tid;
int fd,fd1;
ssize_t rad;
char arr[128]="";
void *zyy(void *p)
{
while(1)
{
bzero(arr,sizeof(arr));
printf("请输入\n");
fgets(arr,sizeof(arr),stdin);
if(write(fd1,arr,sizeof(arr))<0)
{
perror("write");
return NULL;
}
printf("写入数据成功\n");
}
}
int main(int argc, const char *argv[])
{
pthread_create(&tid,NULL,zyy,NULL);
//创建有名管道
if(mkfifo("./fifo",0667)<0)
{
if(errno!=17)
{
perror("mkfifo");//文件存在错误 这是一个允许存在的错误
return -1;
}
}
printf("管道1创建成功\n");
if(mkfifo("./fifo1",0667)<0)
{
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("管道2创建成功\n");
//有名方式打开管道文件 以只读的方式打开open函数阻塞
fd=open("./fifo",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("管道打开成功\n");
fd1=open("./fifo1",O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("管道1打开成功\n");
while(1)
{ bzero(arr,sizeof(arr));
if((rad=read(fd,arr,sizeof(arr)))<0)
{
perror("read");
return -1;
}
if(rad==0)
{
printf("写端关闭\n");
break;
}
printf("%s\n",arr);
if(strcmp(arr,"quit")==0)
{
break;
}
}
close(fd);
close(fd1);
return 0;
}
結果: