[英]Not output is coming when below code is executed in C++ for function overloading
[英]Linux command executed from C code system() function giving different result as compared to when executed from Terminal
我正在使用system()函數從C代碼運行一堆Linux命令。 從C代碼運行這些命令的結果不同於從終端運行這些命令的結果。 例:
std::string name("\\pot\ ");
std::stringstream extractInfoCmd;
extractInfoCmd<<"find . -name \"*.info\" | xargs grep -E \"^PART|^"<<name.c_str()<<"\" >> information.rpt";
std::string extractInfoCmdStr = extractInfoCmd.str();
printf("\n##DEBUG Command: %s\n", extractInfoCmdStr.c_str());
system(extractInfoCmdStr.c_str());
如果我的輸入文件包含以下兩行:
PART: 6
\pot : f
現在,如果我從終端執行相同的命令(從上面的DEBUG日志接收到),則兩行代碼都將顯示。 但是,如果我從C system()函數執行相同的命令,則只會得到第一行,而不會得到第二行:
PART: 6
很長時間以來,我一直在調試此程序,但它的原因並沒有引起我的注意。
您的編譯器將解析name
字符串中的反斜杠,然后使用該字符串來構建extractInfoCmd
字符串,然后將其傳遞給嘗試再次解釋它們的shell( /bin/sh
)。 因此,傳遞給grep
進程的實際字符串不是您想要的。
解決此問題的最佳方法是避免使用system
,而是使用execlp
,您可以在其中分別傳遞每個參數。
也不需要使用管道將信息從find
傳遞到grep
,您可以使用find
本身來完成:
find . -name '*.info' -exec grep -E '^PART|^\\pot\ ' {} \;
或者,直接在C中:
execlp(
"/usr/bin/find",
".",
"-name",
"*.info",
"-exec",
"grep",
"-E",
"^PART|^\\\\pot\\ ",
"{}",
";",
NULL);
您無需在外殼中將輸出通過管道傳遞到文件,而只需在流程中使用pipe
即可直接使用管道來find
的標准輸出,然后可以從中讀取內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.