我有以下代码:
#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
将其cannot open `/sbin/file1' (No such file or directory)
之类的错误消息写入标准输出,而不是标准错误。好像是the one place in their code they use file_printf
instead of file_error
。是的,尽管file_printf
,这在file_error
中似乎是一个严重的疣,所以我不会指望他们很快改变它。