使用pipe()和fork()复制文件的内容

时间:2015-12-17 07:48:10

标签: c linux

已经提出过类似的问题,但他们的解决方案对我没有多大帮助

Program that read file and send it to parent process with pipe

Read/writing on a pipe, accomplishing file copying in C

我试图从文件test.txt(包含单行文本)中读取,将其写入管道,子进程将从管道读取并将内容写入另一个文件。

 /* Read the contents of a file and display it using pipe */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

void main()
{
  char buffer[100];
  char childbuff[100];
  int fd[2], des, bytes, target;

  pipe(fd);

  if(fork()) {
    /* parent process closes the downstream */
    close(fd[0]);

    /* reads the file */
    des = open("test.txt", O_RDONLY);
    bytes = read(des, buffer, sizeof(buffer));

    /* puts data in pipe */
    write(fd[1], buffer, bytes);
  } else {
    /* Child process closes the upstream */
    close(fd[1]);

    /* reads from the pipe */
    read(fd[0], childbuff, sizeof(childbuff));
    close(fd[0]);

    /* output the received string */
    printf("\nReceived string is -- %s", childbuff);
    target = open("copy.txt", O_CREAT, 00777);
    write(target, childbuff, (strlen(childbuff)-1));
  }
}

问题是printf()在终端上打印字符串,也创建了一个名为copy.txt的文件,但没有任何内容被复制到它(似乎write()函数存在问题)

然而,如果我改变

write(target, childbuff, (strlen(childbuff)-1));

write(1, childbuff, (strlen(childbuff)-1));

字符串只是写在我的终端上。

那么在写入文件时我可能做错了什么?

1 个答案:

答案 0 :(得分:4)

您还需要O_WRONLY来写入文件:

target = open("copy.txt", O_CREAT |O_WRONLY, 00777);

请注意,您无法使用strlen()%s将其打印为C字符串。 read(2)没有返回NUL终止字符串。

而是获取从read()读取的字节数,并在write()中使用它:

    ssize_t num_bytes = read(fd[0], childbuff, sizeof(childbuff));

    write(target, childbuff, num_bytes);

您应该检查所有系统调用的返回是否失败。