How redirect stderr to /dev/null in c program(language) on linux
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);
FILE *fdopen(int fildes, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);
[링크 : http://linux.die.net/man/3/freopen]
|
freopen 은 파일 디스크립터를 다시 열어주는 역활을 한다.
위의 예제대로
freopen("/dev/null", "w", stderr);
를 실행하면 /dev/null 을 stderr로 열어주므로, 모든 stderr 메시지가 사라진다.
$ cat redirection.c
#include <stdio.h>
#include <unistd.h>
void main()
{
fprintf(stdout,"test output message\n");
fprintf(stderr,"test error message\n");
}
$ gcc -o a.out redirection.c
$ ./a.out
test output message
test error message
$ ./a.out > /dev/null
test error message
$ ./a.out 2> /dev/null
test output message
|
$ cat redirection_2.c
#include <stdio.h>
#include <unistd.h>
void main()
{
freopen("/dev/null", "w", stderr);
fprintf(stdout,"test output message\n");
fprintf(stderr,"test error message\n");
}
$ gcc -o b.out redirection_2.c
$ ./b.out
test error message
$ ./b.out > /dev/null
$ ./b.out 2> /dev/null
test output message
|
위의 예제 두개를 비교해보면 알 수 있겠지만,
freopen 으로 인해 아래의 예제는 stderr이 출력되지 않는다.