我有一个前端 X 程序,在这个程序中,调用了一个后台程序 a.out。在a.out中,有一些printf
句子。我发现标准输出保存在~/.xsession-errors
. 正常吗?我不想保存这些 printf 内容。除了删除之外,有什么方法可以避免保存它们printf
?
3 回答
Yes, you can use the freopen(3)
function to redirect stdout
to some other file, or to the null device if you'd rather not have any output:
// Discard all further output to standard output for the duration of the
// program (or until the next call to freopen()):
stdout = freopen("/dev/null", "w", stdout);
Depending on how the child program is launched, you can also just redirect its stdout stream. If you're launching it with system(3)
, you can just use shell redirection:
system("./a.out args >/dev/null");
If you're launching it with a fork()
and exec()
pair, then you can redirect the stdout file descriptor in between the fork()
and exec()
to avoid changing anything in the parent process:
// Error checking omitted for expository purposes
pid_t pid = fork();
if(pid == 0)
{
// Child process
int fd = open("/dev/null", O_WRONLY);
dup2(fd, STDOUT_FILENO);
close(fd);
execve("./a.out", argv, envp);
}
There are a few possibilities, by no means an exhaustive list:
When you run your child program, do so in such a way that standard output/error is sent to the bitbucket, such as
system ("myprog >/dev/nul 2>&1");
.Include in that child program your own
printf
varargs-type function which basically does nothing. Provided that function is included before any attempt is made to link in the C runtime libraries, it will use your dummy one in preference.Use
freopen
to redirect standard output and error to the same bitbucket.
Options 2 and 3 require changes to the child program which may or may not be desirable. The first option can be effected by only changing the parent program.
在类似的情况下,我这样做了:
#define printf(...) ;