1

I have the following but I'm worried about $! being overwritten prior to the echo command taking place (I know this is probably a few milliseconds). How do you guys recommend going about this?

sleep 100 & >/dev/null ; echo $! >sleep.pid
Abdo
  • 13,549
  • 10
  • 79
  • 98
  • 1
    What do you mean by "`$!` being overwritten"? There are no commands between the `sleep` and the `echo` so what would overwrite it? – Jonathan Wakely Jul 18 '13 at 09:55
  • 1
    $! is the pid of the most recent background command http://stackoverflow.com/a/5163260/226255 .. What if, between the "firing" of sleep takes place and echo starts (I know it's probably just a millisecond) some other command gets forked? – Abdo Jul 18 '13 at 09:59
  • You have to make sure that in your script no other command is forked... – Basile Starynkevitch Jul 18 '13 at 11:18
  • @BasileStarynkevitch this is my question. How can I get the correct pid while taking this into consideration? – Abdo Jul 18 '13 at 11:28
  • Show more of your script. Or consider switching to a more powerful scripting language (Ocaml, Python, Guile....) – Basile Starynkevitch Jul 18 '13 at 11:30
  • 1
    How do you make sure no other command is forked in your script? **Don't fork another command in your script!** – Jonathan Wakely Jul 18 '13 at 11:33

1 Answers1

2

$! is the PID of the most recent background process in the current shell, not the most recent on the entire box. That would be useless in practice, because you could never know if you got the right value.

The snippet you show in your question cannot possibly return the wrong PID. There is no other background process between the sleep and the echo.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • I get it for sleep.. It was just an example. I tried simulating some concurrency but can't make sure whether we got the right process id so I think discussing this is pointless and, as you suggested above, the only way to guarantee to have $! hold the last pid is to not fork in the first command. I can live with this for now =) – Abdo Jul 18 '13 at 11:58
  • _"the only way to guarantee to have $! hold the last pid is to not fork in the first command"_ Nonsense, just store `$!` as the next command after executing a background command. I don't understand what the problem is, this is really really simple. – Jonathan Wakely Jul 18 '13 at 14:31
  • 1
    I think you missed a key part of my earlier comment: _"Don't fork **another** command in your script!"_ If you run a background command then immediately afterwards `$!` will have the right value, so use it immediately. If you run another process in the background _after_ you've stored `$!` that's fine, the value of `$!` will change but you've already stored the old one. This is really really simple. – Jonathan Wakely Jul 18 '13 at 14:33