1

我有以下代码:

#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。

4

1 回答 1

1

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

于 2020-04-29T00:30:53.893 回答