0

I have to run a system command in a my C++ code:

int val = system( "pacmd list-sink-inputs | grep -c 'state: RUNNING'" );

The command returns the result to val which is desirable, but also val or the return of the call( I can't seem to figure out which one ) also gets written to stdout and prints on the terminal.

Is there a way to redirect the call to NOT write to stdout or anywhere but to val?

ytobi
  • 535
  • 1
  • 9
  • 19

2 Answers2

1

Bash Pipelines will help.

If |& is used, the standard error of command is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |.

Thus you can use the command below

int val = system( "pacmd list-sink-inputs &| grep -c 'state: RUNNING'" );

or

int val = system( "pacmd list-sink-inputs 2>&1| grep -c 'state: RUNNING'" );

Community
  • 1
  • 1
Bjjam
  • 71
  • 6
  • that did no solve the problem, it still gets sent to console – ytobi May 05 '18 at 05:48
  • grep is writing to stderr too, I want it to write to nowhere, bash should just discard the result of grep. – ytobi May 05 '18 at 05:54
  • You can redirect stderr to stdout if grep is writing to stderr too. int val = system( "pacmd list-sink-inputs 2>&1| grep -c 'state: RUNNING' 2>&1" ); – Bjjam May 05 '18 at 06:20
  • And which language do you use? I think you could misuse the function system. Like python, we can use val = subprocess.check_output("pacmd list-sink-inputs 2>&1| grep -c 'state: RUNNING'" ) to set the command result to val. But if we use val = subprocess.call("pacmd list-sink-inputs 2>&1| grep -c 'state: RUNNING'") , the value of val will nerver get the result of the command we call just the retcode. – Bjjam May 05 '18 at 06:27
0

Redirect the output of the last command to the /dev/null does the trick.

The final command looks like this:

int val = system( "pacmd list-sink-inputs | grep -c 'state: RUNNING' > /dev/null" );

Here is a nice post that explains /dev/null.

ytobi
  • 535
  • 1
  • 9
  • 19