Skip to content
Advertisement

Why is the following shell command working when executed directly in command line, but not working when executed through C program using popen/system?

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 :

JavaScript

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:

JavaScript

Advertisement

Answer

In the shell, you’re using the following command:

JavaScript

In C, you’re passing the following to system (and later to popen):

JavaScript

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement