ryan27968
ryan27968

Reputation: 477

Sigkill child process of sh -c "command"

I am working on a project in which I need to loosely recreate supervisord(job control system) in D. I am using spawnShell() as opposed to spawnProcess() for ease of configuring arguments etc. This has the effect of running sh -c "command". However, it returns the PID of sh NOT of the child process(for obvious reasons). This becomes a problem because my program needs to be able to send a SIGKILL to the process if it doesn't respond to a SIGTERM after a certain period of time. I am able to send a SIGTERM no problem(presumably because sh catches the SIGTERM and passes it to it's child process/processes before exiting). However, for again obvious reasons, SIGKILL stops sh before it gets a chance to send a signal to the child process and it's left orphaned. Which brings me to my questions:

A: Can I safely assume that the PID of the spawned process will always be one higher than the PID of sh? It has behaved as such in all my testing so far.

B: If not, then is there a more elegant way(system call or such) to get a child process's PID knowing only the parent process's PID than having my program just execute pgrep -P <sh PID>?

Upvotes: 1

Views: 502

Answers (2)

William Pursell
William Pursell

Reputation: 212248

You just need:

sh -c 'exec command'

the shell replaces itself with your command and gets out of the way, so there is no intermediate process.

No, you cannot assume pids will differ by one.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361635

Can I safely assume that the PID of the spawned process will always be one higher than the PID of sh? It has behaved as such in all my testing so far.

No. Linux is a multitasking OS. While rare, other processes could start in between. Don't rely on a race condition.

If not, then is there a more elegant way (system call or such) to get a child process's PID knowing only the parent process's PID than having my program just execute pgrep -P <sh PID>?

Not really. Trying to navigate the process tree is a sign that your approach is wrong.

You're solving the wrong problem. Get rid of the shell middle man.

Upvotes: 0

Related Questions