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 ); Using Code:
ps ax | grep 'command' One proposed solution is to use Code:
ps -o ppid,pid,command ax | grep 'command' | grep '^[ *]currentPID' 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) |
For the first problem I would use "fork", "execve" and "wait" (man for more info). Something like:
Code:
pid = fork(); |
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 |
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. |