Getting PID of process from bash shell command invoked from MONO C# app

1

1

I have following linux terminal command:

ps -aef | grep -v grep | grep 'TestService.exe' | awk '{print $2}'

which works fine from Linux terminal and retreives PID of wanted process, for example, output is: 5532. However, I have to run upper command from Mono C# application using following code:

Process proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "/bin/bash",
        Arguments = string.Format("-c ps -aef | grep -v grep | grep '{0}' | awk '{{print $2}}'", p),
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = false
    }
};

which is (almost) identical to command, launched from terminal, however, the output is:

testuser+   2184   2160  0 11:43 pts/0    00:00:03 /usr/local/bin/mono-sgen /home/testuser/testuser/MONO/cs/src/testApp/bin/Debug/TestService.exe

but I need only PID column, i.e., PID of a process. Why is output different?

KernelPanic

Posted 2017-03-08T11:01:32.677

Reputation: 97

Answers

1

You need to escape the $, like this

/bin/bash -c "ps -aef | grep -v grep | grep '{0}' | awk '{{print \$2}}'"

If you don't $2 gets interpreted too early by the shell and it ends up like this:

/bin/bash -c "ps -aef | grep -v grep | grep '{0}' | awk '{{print}}'" 

and this will just will print the entire input line

Nifle

Posted 2017-03-08T11:01:32.677

Reputation: 31 337