繁体   English   中英

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

[英]How can a Unix program display output on screen even when stdout and stderr are redirected?

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

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

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

EDIT2:玩了一下,事实证明myprogram,而不是valgrind,正在打印消息,并且如下面的回答,它看起来像gcc堆栈粉碎检测代码正在打印到/ dev / tty

它不是由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);

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

fd = open (_PATH_TTY, O_WRONLY);

_PATH_TTY不是真正的标准,但SingleUnix 实际上要求 /dev/tty存在。

下面是一些示例代码,它完全符合要求(感谢早期的答案指向我正确的方向)。 两者都是用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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM