下面的程序实现的功能是:
writefifo.c完成从打开输入的文件名,然后将内容读取到管道
readfifo.c完成将管道中读到的内容写到输入的文件名中。
writefifo.c :
![]()
#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[N] = {0};
ssize_t n;
if (argc < 2)
{
printf("
usage:%s srcfile\n", argv[0]);
return 0;
}
if (-1 == mkfifo("
fifo", 0666))
//创建管道
{
if (errno != EEXIST)
{
perror("
mkfifo");
exit(-1);
}
}
if ((fd =
open(argv[1], O_RDONLY)) == -1)
//打开要读的文件
{
perror("
open srcfile");
exit(-1);
}
if ((pfd =
open("
fifo", O_WRONLY)) == -1)
//打开管道
{
perror("
open fifo");
exit(-1);
}
while ((n =
read(fd, buf, N)) > 0)
//读文件,当读到末尾时,n为0
write(pfd, buf, n);
//将读到的内容写入管道
close(fd);
close(pfd);
return 0;
}
readfifo.c
![]()
#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[N] = {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;
}