1

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.

Iverson Hsieh
  • 181
  • 1
  • 10
  • I'm not sure it is possible to do this in every scenario. For example, once text has been delivered to the Windows console, it is there for good unless you manually clear the screen. – Tim Biegeleisen Jan 26 '16 at 05:53
  • 3
    Possible duplicate of [C restore stdout to terminal](http://stackoverflow.com/questions/11042218/c-restore-stdout-to-terminal) – paddy Jan 26 '16 at 06:00

3 Answers3

2

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.

rici
  • 234,347
  • 28
  • 237
  • 341
1

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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

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

Community
  • 1
  • 1
csd
  • 934
  • 5
  • 12