Shell script that starts a process, starts another process, then kills the first process
Solution 1
You can use bash job control:
#!/bin/bash
./server &
./client
kill %1
Be sure to put the #!/bin/bash
at the beginning of the script so that bash is used to execute the script (I'm not sure if job control is supported in sh, please correct me if it does).
Solution 2
You can achieve the same result with standard POSIX sh. In sh, when you spawn a process in the background using '&', the PID of the process is stored in the special variable $!. So:
#!/bin/sh
./server &
./client
kill $!
For more complex situations you might want to save the pid:
#!/bin/sh
./server &
serverpid=$!
# ... lots of other stuff
kill $serverpid
Related videos on Youtube
Jez
Updated on September 18, 2022Comments
-
Jez over 1 year
Let's imagine I have a
client
and aserver
on the same machine, and I'd like to script some interaction between them.I would really like a shell script to -
- Start
server
- Put
server
in the background - Start
client
- (wait for
client
to do whatever it does) - Stop
server
I can do most of that already, like this -
./server & ./client
But that leaves
server
running after the script finishes which, apart from anything else, is very untidy.What can I do?
- Start
-
Wuffers almost 13 yearsNo problem! Glad to help!