1

I've a simple shell script like

#!/bin/bash

sh -c "sleep 60" &
exec sleep 120

In using the pstree command, I found something like

`-sleep(11681)---sleep(11682)

The first sleep is due to the sh -c, so even I have execute that sleep in the background, it is now parented at my exec's sleep.

Question: How to detach the first sleep and make the pstree have something like

 -sleep(11681)
 -sleep(11682)
Ryan
  • 5,831
  • 24
  • 72
  • 91

2 Answers2

1

The first sleep is detached already. What's happening is that the sleep 60 is parented by the shell that is running the script, then the exec replaces that shell with the sleep 120, so your sleep 120 is now the parent of your sleep 60. To have them at the same level in the pstree output, simply background the sleep 120 just like you do the sleep 60 instead of exec'ing it.

John
  • 9,070
  • 1
  • 29
  • 34
  • 1
    Keep in mind that as soon as the parent process exits, one or both of your `sleep`s will have a parent of `init` (pid 1), so don't get worried when you don't see them where you expect to in the `pstree` output. – John Jun 17 '14 at 17:19
  • How about if I want to keep the `exec`? I need the `exec` since this script will be used by `supervisord` as process monitoring. I use `sleep` here as only for the ease of demo only – Ryan Jun 19 '14 at 03:52
  • If you keep the exec, then your pstree output will remain the same - i.e. the way you don't want it. Sorry, but in this situation I don't see a way you can have your cake and eat it, too. – John Jun 19 '14 at 11:27
1

sleep 60 & sleep 120 & wait