LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Find PID of /bin/sh command in C++ (https://www.linuxquestions.org/questions/programming-9/find-pid-of-bin-sh-command-in-c-689600/)

Curtor 12-10-2008 10:28 AM

Find PID of /bin/sh command in C++
 
Linux, C++
I want to read a command as an argument to a program, and then run it using:
Code:

int returnValue = execlp( "/bin/sh", "/bin/sh", "-c", command, "; return $?", (char*)NULL );
The catch is, I want to know the PID of the program run using 'command'.

Using
Code:

ps ax | grep 'command'
may return more than one result, so it is not sufficient.

One proposed solution is to use
Code:

ps -o ppid,pid,command ax | grep 'command' | grep '^[ *]currentPID'
and then return the result in the second column. The problem with this is:
1) If the command is something very small and exits almost immediately
(Therefore not occurring in the ps results)
2) The command forks off additional children with similar command names
(Therefore returning more than one possibly correct result)

vladmihaisima 12-10-2008 10:52 AM

For the first problem I would use "fork", "execve" and "wait" (man for more info). Something like:

Code:

pid = fork();

if(fork==0) {
  // child process
  execve(command);
}

// parrent process
r = wait(pid);

For the second problem maybe you could use the "ptrace" feature of linux kernel - to intercept the forks for example. (http://www.linuxjournal.com/article/6100)

ta0kira 12-10-2008 07:37 PM

One problem is that command has a good chance of resulting in multiple processes, such as with redirection, or maybe even sub-shells. If the command can be grepped from a list of running processes, though, then you can probably just skip the call to the shell and exec the command itself. I don't really understand what the purpose of the shell is in your example, and why you wouldn't use system if you need shell interpretation.
ta0kira

Curtor 12-11-2008 09:04 AM

I could use a system call, but a system call just does what my program is already doing. System will exec using /bin/sh -c command and then wait for the call to return. (See http://linux.die.net/man/3/system)

It still presents the same problem for not knowing what the new process ID is.

As ta0kira said, I want to use /bin/sh (or something similar) so that the command may contain shell interpretation.


All times are GMT -5. The time now is 03:45 PM.