The command is : ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
I am running it through adb shell. Basically, I want a list of processes (and certain parameters) which are currently in the run queue. This is working fine if I run it directly through the shell.
However, if I put it in a C program and cross-compile it to run on Android, it’s not working. Only ps -c -p
is working (I have checked that). But on running this ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
, I get the 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
I think the output of ps -c -p
is not being conveyed to tr
, which doesn’t convey it to cut
.
Can you please suggest what’s the issue?
Here’s the code I am using:
#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 status4n"); return -1; } return 0; }
Advertisement
Answer
In the shell, you’re using the following command:
ps -c -p | tr -s " " | cut -d " " -f 2,6-10,13 | grep 'R'
In C, you’re passing the following to system
(and later to popen
):
ps -c -p | tr -s | cut -d -f 2,6-10,13 | grep 'R'
See the difference? Quotes need to be escaped in C source code. Also, when you have trouble like this, be sure to output the relevant data so you can see what is actually happening instead of what you planned. A simple puts(cmd4)
would have revealed this instantly.