为什么下面的shell命令在直接在命令行中执行时有效,而在使用popen/system通过C程序执行时无效?
命令是:为什么下面的shell命令在直接在命令行中执行时有效,而在使用popen/system通过C程序执行时无效?,c,linux,command-line,adb,popen,C,Linux,Command Line,Adb,Popen,命令是:ps-c-p | tr-s”“| cut-d”“-f2,6-10,13 | grep'R' 我正在通过adb shell运行它。基本上,我想要一个当前在运行队列中的进程(和某些参数)列表。如果我直接在shell中运行它,它工作得很好 然而,如果我把它放在一个C程序中并交叉编译以在Android上运行,它就不起作用了。只有ps-c-p在工作(我已经检查过了)。但是运行这个ps-c-p | tr-s“| cut-d”-f2,6-10,13 | grep'R',我得到了输出: usage: t
ps-c-p | tr-s”“| cut-d”“-f2,6-10,13 | grep'R'
我正在通过adb shell运行它。基本上,我想要一个当前在运行队列中的进程(和某些参数)列表。如果我直接在shell中运行它,它工作得很好
然而,如果我把它放在一个C程序中并交叉编译以在Android上运行,它就不起作用了。只有ps-c-p
在工作(我已经检查过了)。但是运行这个ps-c-p | tr-s“| cut-d”-f2,6-10,13 | grep'R'
,我得到了输出:
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
的输出没有被传送到tr
,而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;
}
#包括
#包括
#包括
#包括
#定义BUFSIZE 128
int main(int argc,字符**argv)
{
char*cmd4=“ps-c-p | tr-s”“| cut-d”“-f2,6-10,13 | grep'R”“;
系统(cmd4);
文件*fp;
字符buf[BUFSIZE];
//另一种方法
if((fp=popen(cmd4,“r”))==NULL){
printf(“打开管道4时出错!\n”);
返回-1;
}
while(fgets(buf,BUFSIZE,fp)!=NULL){
//在这里你想做什么就做什么。。。
printf(“cmd4正在运行!”);
printf(“输出:%s”,buf);
}
if(pclose(fp)){
printf(“未找到或退出命令,错误状态为4\n”);
返回-1;
}
返回0;
}
在shell中,您正在使用以下命令:
ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
在C语言中,您要将以下内容传递到system
(稍后传递到popen
):
看到区别了吗?引号需要在C源代码中转义。另外,当你遇到这样的问题时,一定要输出相关的数据,这样你就可以看到实际发生的事情,而不是你计划的事情。一个简单的
puts(cmd4)
会立即揭示这一点。你能在你的C程序中共享调用的代码吗?提供一个。进行编辑。如果你在Linux上,在strace
下运行它,使用-f
选项跟踪所有子进程,并了解通过类似于popen()
的方式传递命令行参数时会发生什么情况。对于怀疑管道是否正在执行的人,请注意错误消息来自管道的第二和第三阶段,而不是第一阶段。如果您想知道为什么这样编译时不会出错,请参阅
ps -c -p | tr -s | cut -d -f 2,6-10,13 | grep 'R'