课堂练习1-管道
检验匿名管道的大小
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int fd[2];
int count=0;
if(pipe(fd)<0)
{
perror("Fail to create pipe");
exit(EXIT_FAILURE);
}
while(1)
{
write(fd[1],"a",sizeof(char));
printf("count=%d.\n",++count);
}
return 0;
}
读写规则验证
当写端不存在时,从管道读数据
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int n;
int fd[2];
int count=0;
char buf[100]={0};
if(pipe(fd)<0)
{
perror("Fail to create pipe");
exit(EXIT_FAILURE);
}
close(fd[1]);
if((n=read(fd[0],buf,sizeof(buf)))<0)
{
perror("Fail to read pipe");
exit(EXIT_FAILURE);
}
printf("read %d bytes:%s\n",n,buf);
return 0;
}
当写端存在时,父进程向管道写数据,子进程从管道读数据
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#define N 10
#define MAX 100
int child_read(int fd)
{
char buf[N];
int n=0;
while(1)
{
n=read(fd,buf,sizeof(buf));
buf[n]='\0';
printf("Read %d bytes:%s\n",n,buf);
if(strncmp(buf,"quit",4)==0)
break;
}
return 0;
}
int father_write(int fd)
{
char buf[MAX]={0};
while(1)
{
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
write(fd,buf,strlen(buf));
sleep(1);
if(strncmp(buf,"quit",4)==0)
break;
}
return 0;
}
int main()
{
int fd[2];
if(pipe(fd)<0)
{
perror("Fail to create pipe");
exit(EXIT_FAILURE);
}
pid_t pid=fork();
if(pid<0)
{
perror("Fail to fork");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
close(fd[1]);
child_read(fd[0]);
}
else
{
close(fd[0]);
father_write(fd[1]);
}
exit(EXIT_SUCCESS);
return 0;
}