繁体   English   中英

如何将标准错误重定向到 /dev/null

[英]How to redirect stderr to /dev/null

我有以下代码:

#include <cstdlib>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <iostream>
#include <string>
#include <vector>

void tokenize( const std::string& str, char delim, std::vector<std::string> &out )
{
    std::size_t start;
    std::size_t end = 0;

    while (( start = str.find_first_not_of( delim, end )) != std::string::npos )
    {
        end = str.find( delim, start );
        out.push_back( str.substr( start, end - start));
    }
}

int main( int argc, char** argv )
{
  if ( argc < 2 )
  {
      std::cout << "Use: " << argv[0] << " file1 file2 ... fileN" << std::endl;
      return -1;
  }

  const char* PATH = getenv( "PATH" );
  std::vector<std::string> pathFolders;

  int fd = open( "/dev/null", O_WRONLY );

  tokenize( PATH, ':', pathFolders );
  std::string filePath;

  for ( int paramNr = 1; paramNr < argc; ++paramNr )
  {
      std::cout << "\n" << argv[paramNr] << "\n-------------------" << std::endl;
      for ( const auto& folder : pathFolders )
      {
          switch ( fork() )
          {
              case -1:
              {
                  std::cout << "fork() error" << std::endl;
                  return -1;
              }
              case 0:
              {
                  filePath = folder + "/" + argv[paramNr];
                  dup2( fd, STDERR_FILENO );
                  execl( "/usr/bin/file", "file", "-b", filePath.c_str(), nullptr );
                  break;
              }
              default:
              {
                  wait( nullptr );
              }
          }
      }
  }

  return 0;
}

我想将诸如“无法打开`/sbin/file1'(没有这样的文件或目录)”之类的消息重定向到/dev/null,但显然错误消息没有重定向到/dev/null。

如何将 STDERR 重定向到 /dev/null?

编辑:我已经用“ls”命令测试了我的代码,并且我得到的错误消息被重定向了。 我认为问题出在这里,“文件”命令不会将错误消息写入 STDERR。

您已成功将标准错误重定向到/dev/null 无论如何,您看到该消息的原因是file将其错误消息写入标准 output cannot open `/sbin/file1' (No such file or directory)而不是标准错误。 这似乎是他们代码中使用file_printf而不是file_error的地方 是的,这似乎是file中的一个严重缺陷,尽管自 1992 年以来一直如此,有评论说这是故意的,所以我不会指望他们很快就会改变它。

暂无
暂无

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

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