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

byt*_*ker 6 c linux

已经有人问过类似的问题,但他们的解决方案对我帮助不大

读取文件并使用管道将其发送到父进程的程序

在管道上读/写,在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));
  }
}
Run Code Online (Sandbox Code Playgroud)

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

但是,如果我改变

write(target, childbuff, (strlen(childbuff)-1));
Run Code Online (Sandbox Code Playgroud)

write(1, childbuff, (strlen(childbuff)-1));
Run Code Online (Sandbox Code Playgroud)

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

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

P.P*_*.P. 7

您还需要O_WRONLY写入文件:

target = open("copy.txt", O_CREAT |O_WRONLY, 00777);
Run Code Online (Sandbox Code Playgroud)

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

而是获取从中读取的字节数read()并将其用于write()

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

    write(target, childbuff, num_bytes);
Run Code Online (Sandbox Code Playgroud)

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