简体   繁体   中英

How to redirect stderr to /dev/null

I have the following code:

#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;
}

I want to redirect messages like "cannot open `/sbin/file1' (No such file or directory)" to /dev/null, but apparently the error messages aren't redirected to /dev/null.

How can I redirect STDERR to /dev/null?

Edit: I've tested my code with an 'ls' command, and the error message that I've got there was redirected. What I think the issue is here, that the 'file' command doesn't write error message to STDERR.

You are successfully redirecting standard error to /dev/null . The reason you're seeing that message anyway is that file writes its error messages like cannot open `/sbin/file1' (No such file or directory) to standard output , not to standard error. This seems like the one place in their code they use file_printf instead of file_error . And yes, this seems like a serious wart in file , though it's been that way since 1992 with a comment saying it's on purpose , so I wouldn't count on them changing it any time soon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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