即使重定向stdout和stderr,Unix程序如何在屏幕上显示输出?

时间:2015-07-08 19:15:53

标签: c++ linux

我在我的Ubuntu机器上运行了一个程序(实际上是valgrind),并将stdout和stderr重定向到不同的文件。我很惊讶地看到屏幕上出现一条短信 - 这怎么可能?我怎么能在C ++程序中自己做到这一点?

编辑:这是我使用的命令和输出:

$ valgrind ./myprogram > val.out 2> val.err
*** stack smashing detected ***: ./myprogram terminated

EDIT2:再玩一下,事实证明myprogram,而不是valgrind,正在打印消息,如下所示,它看起来像gcc stack粉碎检测代码正在打印到/ dev / tty < / p>

3 个答案:

答案 0 :(得分:16)

它不是由valgrind编写的,而是glibc而你的./myprogram正在使用glibc:

#define _PATH_TTY   "/dev/tty"

/* Open a descriptor for /dev/tty unless the user explicitly
   requests errors on standard error.  */
const char *on_2 = __libc_secure_getenv ("LIBC_FATAL_STDERR_");
if (on_2 == NULL || *on_2 == '\0')
  fd = open_not_cancel_2 (_PATH_TTY, O_RDWR | O_NOCTTY | O_NDELAY);

if (fd == -1)
  fd = STDERR_FILENO;

...
written = WRITEV_FOR_FATAL (fd, iov, nlist, total);

以下是glibc的一些相关部分:

void
__attribute__ ((noreturn))
__stack_chk_fail (void)
{
  __fortify_fail ("stack smashing detected");
}

void
__attribute__ ((noreturn))
__fortify_fail (msg)
     const char *msg;
{
  /* The loop is added only to keep gcc happy.  */
  while (1)
    __libc_message (2, "*** %s ***: %s terminated\n",
            msg, __libc_argv[0] ?: "<unknown>");
}


/* Abort with an error message.  */
void
__libc_message (int do_abort, const char *fmt, ...)
{
  va_list ap;
  int fd = -1;

  va_start (ap, fmt);

#ifdef FATAL_PREPARE
  FATAL_PREPARE;
#endif

  /* Open a descriptor for /dev/tty unless the user explicitly
     requests errors on standard error.  */
  const char *on_2 = __libc_secure_getenv ("LIBC_FATAL_STDERR_");
  if (on_2 == NULL || *on_2 == '\0')
    fd = open_not_cancel_2 (_PATH_TTY, O_RDWR | O_NOCTTY | O_NDELAY);

  if (fd == -1)
    fd = STDERR_FILENO;

  ...
  written = WRITEV_FOR_FATAL (fd, iov, nlist, total);

答案 1 :(得分:3)

该消息很可能来自GCC的堆栈保护功能或glib本身。如果它来自GCC,则使用fail()函数输出,该函数直接打开/dev/tty

fd = open (_PATH_TTY, O_WRONLY);

_PATH_TTY并非真正标准,但/dev/tty存在的SingleUnix actually demands

答案 2 :(得分:2)

以下是一些示例代码,它完全符合要求(感谢先前的答案指向了正确的方向)。两者都是用g ++编译的,即使重定向stdout和stderr,它也会在屏幕上打印一条消息。

对于Linux(Ubuntu 14):

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main( int, char *[]) {

    printf("This goes to stdout\n");

    fprintf(stderr, "This goes to stderr\n");

    int ttyfd = open("/dev/tty", O_RDWR);
    const char *msg = "This goes to screen\n";
    write(ttyfd, msg, strlen(msg));
}

对于Windows 7,使用MinGW:

#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <conio.h>

void writeConsole( const char *s) {
    while( *s) {
        putch(*(s++));
    }
}

int main( int, char *[]) {  
    printf("This goes to stdout\n");

    fprintf(stderr, "This goes to stderr\n");

    writeConsole( "This goes to screen\n");
}