> Hi,
> I am attempting to temporarily close stdout, do some processing (that
> has results sent to stdout, and I don't want users to see) and then do
> more processing that has results that I want the user to see ...
> I have tried working with dup2, fdopen, freopen, but I haven't got the
> right combination. Do I need to use fcntl or ioctl ?
> Thanks,
> Ken Sullivan
Unix system, so I followup this post to comp.unix.programmer.
Here is a sample program, I hope it helps you :
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int stdout_fileno;
int null_fileno;
printf("Hello ");
printf("world");
/*
** dup & close STDOUT_FILENO
** Don't fclose stdout because it could not be reopened
** Flushing stdout is necessary because it is line-buffered by
** default. If this was not done, the above two strings would be
lost,
** because the string "world" is not terminated by a new-line
char.
*/
fflush(stdout);
if ((stdout_fileno = dup(STDOUT_FILENO)) < 0) {
perror("dup");
exit(EXIT_FAILURE);
}
/*
** Redirect STDOUT_FILENO to /dev/null to make printf happy
*/
if ((null_fileno = open("/dev/null", O_WRONLY)) < 0) {
perror("open");
exit(EXIT_FAILURE);
}
if (dup2(null_fileno, STDOUT_FILENO) < 0) {
perror("dup2");
exit(EXIT_FAILURE);
}
close(null_fileno);
printf("Goobye cruel world");
/*
** restore STDOUT_FILENO & close useless stdout_fileno
** Flush stdout to clear internal buffer before restoring
*/
fflush(stdout);
if (dup2(stdout_fileno, STDOUT_FILENO) < 0) {
perror("dup2");
exit(EXIT_FAILURE);
}
close(stdout_fileno);
printf("\nHello, I'm working again\n");
return(EXIT_SUCCESS);
This program prints :Quote:}
Hello world
Hello, I'm working again
--
Herve Couppe de Lahongrais (SEU) | Eurocontrol Experimental Centre