【问题标题】:Redirect standard output to file and re-establish the standard output with function将标准输出重定向到文件并使用函数重新建立标准输出
【发布时间】:2019-10-04 15:50:30
【问题描述】:

我必须创建一个函数,将标准输出临时重定向到一个文件名“file”,然后执行函数f,然后重新建立原始标准输出。

由于我显然不擅长 shell 和 C,所以我很难实现它。我知道我必须使用 dup() 和 dup2() 但我不知道如何使用它们。


void redirect_to (void (*f)(void), char *file)
{
 int fd = open(file, O_CREAT | O_TRUNC | O_WRONLY, 0644);
 int old = dup(file);
 dup2(fd, old);
 f();
 close(fd);
}

我很确定我做错了,但不明白该怎么做。 非常感谢。。

【问题讨论】:

  • stdout 在 fd 1 上,我在您的代码中看不到任何引用该事实的地方
  • 调试你的代码并观察它们的文件描述符。实验并思考结果。向我们展示一些努力,如果您有具体问题,请回来edit您的问题,并提供minimal reproducible example

标签: c redirect dup2 redirectstandardoutput dup


【解决方案1】:

在程序中有几种方法可以将输出“重定向”到文件,执行函数,然后在该位置恢复原始输出。

首先,如果您只是重新考虑您的编程任务并更改您将传递给“重定向”函数的函数的函数接口,那么您实际上不需要进行任何文件描述符调整:

RET_TYPE redirect_and_call_v1(RET_TYPE(*funct_to_be_called)(int descriptor_to_write_to), int fd_to_be_used_as_output)
{
    return funct_to_be_called(fd_to_be_used_as_output);
}

您将从这个示例中看到,我稍微修改了您的 API,以便将已打开的描述符传递给 redirect_and_call_v1 函数(因为这样您可以使用自己的标准输出作为重定向文件描述符,并且你不要强迫它成为一个文件)并且我已经将那个精确的描述符作为参数传递给funct_to_be_called函数,所以它知道在哪里写东西。

在第二个版本中,我会尊重您的调用接口,假设您无法控制要作为参数传递的函数将写入打开描述符(您必须知道)的位置,并且您希望它保存该描述符描述符用于稍后恢复它,然后将其重定向到我们要使用的描述符。

/* do error checking */
#define CHECK_ERR(var, name, exit_code) do {          \
        if((var) < 0) {                               \
            fprintf(stderr, "ERROR: " name ": %s\n",  \
                strerror(errno));                     \
            exit(exit_code);                          \
        }                                             \
    } while(0)

RET_TYPE redirect_and_call_v2(
        RET_TYPE(*funct_to_be_called)(void), 
        int fd_to_be_used_in_function_for_output, 
        int fd_funct_uses_to_write)
{
    /* save a copy descriptor, so we can overwrite the fd the one
     * function uses to write */
    int saved_old_fd = dup(fd_funct_uses_to_write);
    CHECK_ERR(saved_old_fd, "dup", 1);

    /* now, we change the descriptor the function uses to write by the one we want
     * it to be used for output */
    int res = dup2(fd_to_be_used_in_function_for_output, fd_funct_uses_to_write);
    CHECK_ERR(res, "dup2", 2);

    /* now, we call the function */
    RET_TYPE res2 = funct_to_be_called();

    /* now restore descriptors to what they where. For this, we use the saved
     * file descriptor */
    res = dup2(saved_old_func, fd_funct_uses_to_write);

    /* close the saved descriptor, as we dont need it anymore */
    close(saved_old_func);

    /* and finally, return the funct_to_be_called return value */
    return res2;
}

最终的完整示例如下所示(此解决方案的 github 存储库提供here):

文件main.c

/* main.c --- main program for the test of temporary redirection
 * of a file descriptor.
 * fputs(3) prints to stdout, but we are going to intersperse
 * printf(3) calls, with puts(3) calls (with temporary
 * redirection) to see that the temporary redirection actually
 * works. All the output will be \n terminated, so we are sure
 * that buffers are flushed out on each call.
 *
 * Author: Luis Colorado <luiscoloradourcola@gmail.com>
 * Date: Sat Oct 12 13:28:54 EEST 2019
 * Copyright: (C) LUIS COLORADO.  All rights reserved.
 * License: BSD.
 */

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

#include "redirect.h"

/* this is our unbuffering simulation of the puts(3) function,
 * as trouble will come if we don't consider the flushing of
 * buffers properly, and I don't want to overcomplicate things
 * with stdio buffering idiosyncracies.  Function forcibly writes
 * its output to standard output, so to make it use a different
 * descriptor, we need to redirect standard output to a different
 * place before call, and restore it later.*/
ssize_t output_function(const char *s)
{
        /* ensure all output is flushed before returning back */
        return write(1, s, strlen(s));
}

void do_usage(const char *progname)
{
        fprintf(stderr,
                "Usage: %s [ file ... ]\n"
                "where 'file' is the output file to redirect output to.\n"
                "\n"
                "The program just uses a different string to output to both,\n"
                "standard output and the indicated filename, to thow the workings\n"
                "of output redirection.  I have wrapped the call to fputs(3) in a\n"
                "function in order to show that we need to call fflush to flush\n"
                "the buffers out to the file descriptor, before returning, or the\n"
                "wrong things will be written to the output descriptors. (this is\n"
                "specially true for files, that do full buffering)\n",
                progname);
}

int main(int argc, char **argv)
{
        int i;
        if (argc == 1) {
                do_usage(argv[0]);
        } else for (i = 1; i < argc; i++) {
                char buffer[1024];

                /* text we are going to write multiple times */
                snprintf(buffer, sizeof buffer,
                        "%d: file = %s\n", i, argv[i]);

                /* we call our output function first, to see output going
                 * to it's normal output descriptor */
                output_function(buffer);

                /* create a file we are going to write message into */
                int fd_to_redirect_output = open(
                                argv[i],
                                O_WRONLY | O_CREAT | O_TRUNC,
                                0666);

                /* call our function with the message and the redirection
                 * done before the call and restored after */
                int res = redirect_and_call(output_function,
                                        fd_to_redirect_output, /* descriptor to write
                                                                                        * output to */
                                        1, /* stdout is file descriptor 1 */
                                        buffer); /* write the string to the file. */

                /* write another message to see redirection was restored
                 * properly */
                output_function("done\n");
        }
        exit(EXIT_SUCCESS);
} /* main */

文件redirect.h

/* redirect.h --- definitions for the module redirect.c
 * Author: Luis Colorado <luiscoloradourcola@gmail.com>
 * Date: Sat Oct 12 13:24:54 EEST 2019
 * Copyright: (C) 2019 LUIS COLORADO.  All rights reserved.
 * License: BSD.
 */
#ifndef _REDIRECT_H
#define _REDIRECT_H

/* our redirect_and_call will return int, as fputs(3) returns
 * int, and will need an extra parameter, so it can call
 * fputs, and pass it the proper parameter. */
typedef ssize_t RET_TYPE;

RET_TYPE redirect_and_call(
        RET_TYPE (*funct_to_be_called)(const char*s), 
        int fd_to_write_to,
        int fd_funct_uses_as_output,
        const char *parameter_for_the_call);

#endif /* _REDIRECT_H */

文件redirect.c

/* redirect.c --- function to create a temporary redirect of a
 * file descriptor in order to execute a function (passed as a
 * parameter) with that descriptor redirected so it will output
 * to the redirected desriptor, instead of to the one it used to.
 * We'll use puts(3) as an example of a function that is
 * hard wired to print into stdout (fd = 1) and to make it to
 * write to a named file instead.
 *
 * Author: Luis Colorado <luiscoloradourcola@gmail.com>
 * Date: Sat Oct 12 13:04:45 EEST 2019
 * Copyright: (C) 2019 LUIS COLORADO.  All rights reserved.
 * License: BSD.
 */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "redirect.h"

#define F(_f) __FILE__":%d:%s: " _f, __LINE__, __func__

#define CHECK_ERR(var, status, name) do {     \
                if ((var) < 0) {                      \
                        fprintf(stderr,                   \
                                F("%s: %s\n"),                \
                                name, strerror(errno));       \
                        exit(status);                     \
                }                                     \
        } while(0)

RET_TYPE redirect_and_call(
        RET_TYPE (*funct_to_be_called)(const char*s), 
        int fd_to_write_to,
        int fd_funct_uses_as_output,
        const char *parameter_for_the_call)
{
   /* save a copy descriptor, so we can overwrite the fd the one
     * function uses to write */
    int saved_old_fd = dup(
                        fd_funct_uses_as_output);
    CHECK_ERR(saved_old_fd, 1, "dup");

    /* now, we change the descriptor the function uses to write
         * by the one we want it to be used for output */
    int res = dup2(
                        fd_to_write_to,
                        fd_funct_uses_as_output);
    CHECK_ERR(res, 2, "dup2");

    /* now, we call the function */
    RET_TYPE res2 = funct_to_be_called(parameter_for_the_call);

    /* now restore descriptors to what they where. For this, we
         * use the saved file descriptor */
    res = dup2(saved_old_fd, fd_funct_uses_as_output);

    /* close the saved descriptor, as we dont need it anymore */
    close(saved_old_fd);

    /* and finally, return the funct_to_be_called return value */
    return res2;
} /* redirect_and_call */

文件Makefile

# Makefile --- Makefile for the test program.
# Author: Luis Colorado <luiscoloradourcola@gmail.com>
# Date: Sat Oct 12 13:43:03 EEST 2019
# Copyright: (C) 2019 LUIS COLORADO.  All rights reserved.
# License: BSD.

targets = redirect
toclean = $(targets)
RM              ?= rm -f

all: $(targets)
clean:
        $(RM) $(toclean)

redirect_objs = main.o redirect.o
toclean += $(redirect_objs)

redirect: $(redirect_deps) $(redirect_objs)
        $(CC) $(LDFLAGS) -o $@ $($@_objs) $($@_ldflags) $($@_ldlibs)

【讨论】:

    【解决方案2】:

    您的代码很接近,这是一个完整的工作示例:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <errno.h>
    
    void some_func() {
        printf("This gets written to file.\n");
        fflush(stdout);
    }
    
    void redirect_stdout(void (*some_func)(void), char *file) {
        printf("Preparing to redirect to file:\n");
        fflush(stdout);
        //sys has three streams (0)stdin (1)stdout (2)stderr
        //use dup to store the stdout for restoration later:
        int saved_stdout = dup(1);
        int fw = open(file, O_CREAT | O_TRUNC | O_WRONLY, 0644);
        //checks for open failure and cleans up resources / prints errors if so
        if (fw < 0) {
            printf("Failed to open %s.\n", file);
            perror("Error: ");
            if (close(saved_stdout) != 0) {
                perror("Error: ");
            }
            return;
        }
        dup2(fw,1);    //use 1 as it is the integer assigned to stdout
        some_func();
        if (close(fw) != 0) {               //checks for bad file descriptor
            perror("Error: ");
        }
        dup2(saved_stdout, 1);
        if (close(saved_stdout) != 0) {     //checks for bad file descriptor
            perror("Error: ");
        }
    }  
    
    int main(void) {
        char filename[] = "stdout_content.txt";
        redirect_stdout(some_func, filename);
        printf("Stdout now back to terminal output.\n");
        return 0;
    }
    

    查看 dup、dup2、open、close 等的 Linux 手册页。请注意,我首先使用 freopen 进行了尝试,但无法找到将 stdout 恢复到终端的任何方法,并且似乎还有其他使用 fork 的方法() 等涉及更多。 http://www.microhowto.info/howto/capture_the_output_of_a_child_process_in_c.html

    【讨论】:

    • 如果open() 失败,您会报告一个错误(在标准输出上;这应该是标准错误,又名stderr),然后继续,就好像没问题一样。你的错误处理需要在报错后返回,或者退出。其余代码或多或少都足够好。处理其他系统调用的错误很简单,但open() 是检查错误的关键。您可能会考虑在明智的情况下使用fflush(stdout),以确保按预期写入输出。如果程序使用 I/O 重定向 (./program &gt; other.out) 运行,您可能无法获得想要的结果。
    • @JonathanLeffler 感谢您的评论,我尝试适当地实施。
    【解决方案3】:

    我终于得到了正确的答案,所以这里是如何将标准输出临时重定向到一个文件名“file”,然后执行函数f,然后重新建立原来的标准输出:

    
    void redirect_stdout (void (*f)(void), char *file)
    {
     int fd = open(file, O_CREAT | O_TRUNC | O_WRONLY, 0644);
     int savefd = dup(1);
     dup2(fd, 1);
     f();
     dup2(savefd, 1);
     close(fd);
     close(savefd);
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多