comp.lang.c
[Top] [All Lists]

Re: Temporarily close stdout?

Subject: Re: Temporarily close stdout?
From: Richard Tobin
Date: 30 Apr 2008 13:56:05 GMT
Newsgroups: comp.lang.c

In article <42aa5189-6a17-41d9-9528-4c1361d99170@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
Joakim Hove  <joakim.hove@xxxxxxxxx> wrote:

>  /* Temporarily redirect stdout -> /dev/null */
>  stdout = freopen("/dev/null" , "w" , stdout);

Don't assign the result to stdout.  freopen() changes stdout itself.

>  /* restore stdout */
>  stdout = freopen("/dev/stdout" , "w" , stdout);

>But - the last freopen() fails with 2:No such file or directory.

Probably it closes stdout before trying to open /dev/stdout.

The dup() approach with /dev/fd would be something like (not tested):

    char buf[20];
    int saved_stdout = dup(1);

    freopen("/dev/null", "w", stdout);
    lsb_submit( &request , &reply );
    sprintf(buf, "/dev/fd/%d", saved_stdout);
    freopen(buf, "w", stdout);

To avoid dup(), but still relying on /dev/stdout, do

    FILE *mystdout = fopen("/dev/stdout", w);
    freopen("/dev/null", "w", stdout);

and change your code to write to write to mystdout instead of stdout.

You'd be wise to ask in a unix, linux or posix newsgroup, because
there may be subtleties to the workings of /dev/stdout and /dev/fd/.

-- Richard
-- 
:wq

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy