将标准输出重定向到文件

时间:2019-03-31 12:49:08

标签: c linux

我必须修改此代码。子进程应将标准输出重定向到文本文件。

我认为我应该对dup2和exec做某事,但我不知道该怎么办。

我阅读了this ref和this

但是它没有帮助我,可能我做错了。

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main ()
{
    int fds[2];
    pid_t pid;
    /* Create a pipe. File descriptors for the two ends of the pipe are placed in fds. */
    /* TODO add error handling for system calls like pipe, fork, etc. */
    pipe (fds);
    /* Fork a child process. */
    pid = fork ();
    if (pid == (pid_t) 0) {
        /* This is the child process. Close our copy of the write end of the file descriptor. */
        close (fds[1]);
        /* Connect the read end of the pipe to standard input. */
        dup2 (fds[0], STDIN_FILENO);
        /* Replace the child process with the "sort” program. */
        execlp ("sort", "sort", NULL);
    } else {
        /* This is the parent process. */
        FILE* stream;
        /* Close our copy of the read end of the file descriptor. */
        close (fds[0]);
        /* Convert the write file descriptor to a FILE object, and write to it. */
        stream = fdopen (fds[1], "w");
        fprintf (stream, "This is a test.\n");
        fprintf (stream, "Hello, world.\n");
        fprintf (stream, "My dog has fleas.\n");
        fprintf (stream, "This program is great.\n");
        fprintf (stream, "One fish, two fish.\n");
        fflush (stream);
        close (fds[1]);
        /* Wait for the child process to finish. */
        waitpid (pid, NULL, 0);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您对dup2所做的操作是将父级stdout连接到孩子的stdin,而孩子的stdout无需重定向。因此,childr会将排序后的字符串打印到stdout。 接下来,您需要打开一个文本文件,并对其进行dup2的操作stdout。例如execlp

之前的内容
int outfd=open("/tmp/output",O_WRONLY|O_TRUNC|O_CREAT,0600);
dup2(outfd,STDOUT_FILENO);
execlp ("sort", "sort", NULL);

您还需要#include <fcntl.h>来拥有文件标志。