您的位置:首页 > 其它

利用FIFO进行文件拷贝一例

2013-03-08 19:28 169 查看
下面的程序实现的功能是:

[b]writefifo.c完成从打开输入的文件名,然后将内容读取到管道[/b]

readfifo.c完成将管道中读到的内容写到输入的文件名中。

[b]writefifo.c :[/b]

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#define N 64

int main(int argc, char *argv[])
{
int fd, pfd;
char buf
= {0};
ssize_t n;

if (argc < 2)  //检查输入的参数是否合法
{
printf("usage:%s destfile\n", argv[0]);
return 0;
}

if (-1 == mkfifo("fifo", 0666))   //创建一个名称为fifo的管道
{
if (errno != EEXIST)   //如果创建错误,看错误码是否为EEXIST,即看要创建的管道是否已经存在
{
perror("mkfifo");
exit(-1);
}
}

if ((fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1) //打开要写的文件
{
perror("open destfile");
exit(-1);
}

if ((pfd = open("fifo", O_RDONLY)) == -1)  //打开管道
{
perror("open fifo");
exit(-1);
}

while ((n = read(pfd, buf, N)) > 0)  //读管道,当读到n为0时,说明写端已经关闭
write(fd, buf, n);  //将读到的内容写到文件中

close(fd);  //关闭要写的文件
close(pfd);  //关闭管道

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: