[英]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.