首页 > 解决方案 > 将标准输出重定向到文件并使用函数重新建立标准输出

问题描述

我必须创建一个函数,将标准输出临时重定向到文件名“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);
}

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

标签: credirectdup2redirectstandardoutputdup

解决方案


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

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

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 存储库):

文件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)


推荐阅读