0

In Bash we can run programs like this

./mybin && echo "OK"

and this

./mybin || echo "fail"

But how do we attach success or fail commands to existing process?

Edit for explaination:

Now we are running ./mybin .

When mybin exits with or without error it will do nothing, but during mybin is running, how can I achieve the same effect like I started the process like ./mybin && echo ok || echo fail ?

In both shell script and python programming way would be awesome, thanks!

est
  • 11,429
  • 14
  • 70
  • 118

1 Answers1

3

But how do we attatch sucess or fail commands to existing already running process?

Assuming you're referring to a command that is run in the background, you can use wait to wait for that command to finish and retrieve its return status. For example:

./command &  # run in background
wait $! && echo "completed successfully"

Here I used $! to get the PID of the backgrounded process, but it can be the PID of any child process of the shell.

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
  • Does this work with any daemons in the background with the same uid/gid? How do I do this in program? – est Sep 20 '12 at 08:24
  • I believe only a parent process can retrieve the exit status. If you explain further what the end goal is, perhaps someone can give you more specific help. There's a chance this may be an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Shawn Chin Sep 20 '12 at 08:26
  • then how does `./mybin && echo ok` work? isn't `echo` a child-process? – est Sep 20 '12 at 08:27
  • When `./mybin` completes, the shell sees the return code and uses that to determine if `echo` should be run. `echo` does not see the return code. Both `mybin` and `echo` are child processes of the shell. – Shawn Chin Sep 20 '12 at 08:30
  • thanks. So what `wait` does is polling the pid to see if it stops? Any way to do this in system signal way? (no polling) – est Sep 20 '12 at 08:32
  • 1
    Yes, you can do that from ./mybin itself. If it is a bash script, use [`trap`](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html). – Shawn Chin Sep 20 '12 at 08:36