Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link two processes Bash

Tags:

bash

I have two command line programs, a client application and a server application it talks to.

The client depends on the server running in the background. I can launch both via:

java -jar server.jar & java -jar client.jar

When I kill the client, however, the server remains in the background. Is there a way to link the two so that if the client dies, the server dies?

like image 795
Allyl Isocyanate Avatar asked Dec 03 '25 16:12

Allyl Isocyanate


2 Answers

Run the server job in the background and store process id using $!. Then run the client. After the client exits, kill the server using the stored pid, like this:

java  -jar server.jar &
server=$!
java -jar client.jar
kill $server

shorter: no need to store PID of the background process, there's only one

java  -jar server.jar &
java -jar client.jar
kill $!
like image 169
Jean-François Fabre Avatar answered Dec 06 '25 10:12

Jean-François Fabre


There is no way to link them, but you can manage the processes explicitly.

java -jar server.jar & server_pid=$!
java -jar client.jar
kill $server_pid

The server runs in the background, then the client runs in the foreground. The script blocks at this point, so when the client exits, the script proceeds with the next command, which kills the server.

like image 28
chepner Avatar answered Dec 06 '25 11:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!