Iverson Hsieh
Iverson Hsieh

Reputation: 181

How to rollback redirected stdio in C?

Round 1

From some examples, I know how to redirect stdio to null.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd = open("/dev/null", O_RDWR);
    int in, out, err;

    if (fd < 0) {
        perror("open file error!");

        return -1;
    }

    printf("test1\n");

    dup2(fd, STDIN_FILENO);
    dup2(fd, STDOUT_FILENO);
    dup2(fd, STDERR_FILENO);

    printf("test2\n");

    close(fd);

    return 0;
}

After I execute the code, my console shows:

test1

test2 is redirected to /dev/null.

However, now, I would like to rollback stdio from /dev/null to standard input and output.

How do I do it?

Round 2

Thank for your reply.

Actually, I suffer a problem that a program redirects stdio (such as example 1) and forks my program (such as example 2).

example 1
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd = open("/dev/null", O_RDWR);

    if (fd < 0) {
        perror("open file error!");

        return -1;
    }

    printf("test1\n");

    dup2(fd, STDIN_FILENO);
    dup2(fd, STDOUT_FILENO);
    dup2(fd, STDERR_FILENO);

    execl("hello_world", NULL);

    close(fd);

    return 0;
}
example 2
#include <stdio.h>

int main()
{
    printf("Hello World!\n");

    return 0;
}

After I run example 1, my console shows:

test1

How do I change example 2 to redirect the printf() to console? Thank you.

Upvotes: 1

Views: 263

Answers (3)

csd
csd

Reputation: 944

For your round2 question, exec call and similar preserve open file descriptors, which means you need to revert what you did either before calling execl, see this for an example on how to save/restore them: Re-opening stdout and stdin file descriptors after closing them

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148975

Provided you do have a controlling terminal (what the /dev/null idiom suggests), you should be able to redirect output to /dev/tty.

But you should be aware that true daemon processes like the one started from cron have no controlling terminal and in that case /dev/tty would not be defined.

Upvotes: 1

rici
rici

Reputation: 241791

A simple solution would be to save the initial file descriptors (which you should not assume are the same) using dup, and then restore them later using dup2.

Upvotes: 2

Related Questions