[英]Why is the following shell command working when executed directly in command line, but not working when executed through C program using popen/system?
命令是: ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
我通過 adb shell 運行它。 基本上,我想要一個當前在運行隊列中的進程(和某些參數)列表。 如果我直接通過 shell 運行它,它工作正常。
但是,如果我把它放在 C 程序中並交叉編譯它以在 Android 上運行,它就不起作用。 只有ps -c -p
有效(我已經檢查過了)。 但是在運行這個ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
,我得到 output:
usage: tr [-cds] SET1 [SET2]
Translate, squeeze, or delete characters from stdin, writing to stdout
-c/-C Take complement of SET1
-d Delete input characters coded SET1
-s Squeeze multiple output characters of SET2 into one character
tr: Needs 1 argument
usage: cut OPTION... [FILE]...
Print selected parts of lines from each FILE to standard output.
-b LIST select only these bytes from LIST.
-c LIST select only these characters from LIST.
-f LIST select only these fields.
-d DELIM use DELIM instead of TAB for field delimiter.
-s do not print lines not containing delimiters.
-n don't split multibyte characters (Ignored).
cut: Needs -fcb
我認為ps -c -p
的 output 沒有被傳送到tr
,它沒有傳送到cut
。 你能提出什么問題嗎?
這是我正在使用的代碼:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 128
int main(int argc,char **argv)
{
char *cmd4 = "ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'";
system(cmd4);
FILE *fp;
char buf[BUFSIZE];
// Another method
if ((fp = popen(cmd4, "r")) == NULL) {
printf("Error opening pipe4!\n");
return -1;
}
while (fgets(buf, BUFSIZE, fp) != NULL) {
// Do whatever you want here...
printf("cmd 4 running!");
printf("OUTPUT: %s", buf);
}
if(pclose(fp)) {
printf("Command not found or exited with error status4\n");
return -1;
}
return 0;
}
在 shell 中,您使用以下命令:
ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
在 C 中,您將以下內容傳遞給system
(然后傳遞給popen
):
ps -c -p | tr -s | cut -d -f 2,6-10,13 | grep 'R'
看到不同? 引用需要在 C 源代碼中進行轉義。 另外,當你遇到這樣的麻煩時,一定要 output 相關數據,這樣你就可以看到實際發生的事情而不是你計划的事情。 一個簡單的puts(cmd4)
會立即揭示這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.