2

我有一个前端 X 程序,在这个程序中,调用了一个后台程序 a.out。在a.out中,有一些printf句子。我发现标准输出保存在~/.xsession-errors. 正常吗?我不想保存这些 printf 内容。除了删除之外,有什么方法可以避免保存它们printf

4

3 回答 3

2

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);
}
于 2013-05-23T02:33:28.817 回答
1

There are a few possibilities, by no means an exhaustive list:

  1. 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");.

  2. 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.

  3. 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.

于 2013-05-23T02:33:12.697 回答
0

在类似的情况下,我这样做了: #define printf(...) ;

于 2013-05-23T02:38:30.927 回答