linux学习笔记7-管道
管道
- 有名管道是持久稳定的.
- 有名管道存在于文件系统中
- 比匿名管道功能更强大,因为不需要父子进程就可以交换数据
mkfifo创建管道和unlink删除管道
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //unlink所需头文件
#include <sys/types.h> //mkfifo所需头文件
#include <sys/stat.h> //mkfifo所需头文件
int main(int argc,char *argv[])
{
int result = mkfifo("fifo1",0666); //创建名称为fifo1的管道
if(result == -1)
{
printf("create fifo failed!\n");
return -1;
}
else
{
result = unlink("fifo1"); //删除名称为fifo1的管道
if(result == -1)
{
printf("delete fifo failed!\n");
return -1;
}
printf("delete fifo success!\n");
}
return 0;
}
管道的写入
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int len = 0;
char buf[100] ;
memset(buf,0,sizeof(buf)); //将buf数组清空
int fd = open("fifo1",O_WRONLY); //以写入的方式打开名称为fifo1的管道
while(1)
{
scanf("%s",buf); //可以用read(STDIN_FILE,buf,sizeof(buf));
if(buf[0] == '0')
{
break;
}
write(fd,buf,sizeof(buf)); //将内容写入到管道中
memset(buf,0,sizeof(buf)); //将buf数组清空
}
close(fd); //使用完毕之后,关闭管道
return 0;
}
管道的读取
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int len = 0;
char buf[100];
memset(buf,0,sizeof(buf)); //将buf数组初始为0
int fd = open("fifo1",O_RDONLY); //以只读的方式打开名称为fifo1的管道
while((len=read(fd,buf,sizeof(buf)))>0) //从管道中读取内容
{
printf("%s\n",buf);
memset(buf,0,sizeof(buf)); //将buf数组清空
}
close(fd); //管道和文件一样,使用完毕一定要关闭
return 0;
}
秋风
2016-11-23