How to run a program and get its PID in the background

9,695

As you start the java process with exec, its PID will be the same as the one of the shell script. So you can do

echo $$ > pid
exec java ...
Share:
9,695

Related videos on Youtube

Ivan
Author by

Ivan

Updated on September 18, 2022

Comments

  • Ivan
    Ivan over 1 year

    I have a Minecraft server startup script that looks like this:

    #!/bin/bash
    cd "$(dirname "$0")"
    exec java -Xmx4096M -Xms4096M -jar minecraft_server.jar
    

    How do I get java process's PID while being able to enter input into the Java process?

    if I change the exec line to

    exec java -Xmx4096M -Xms4096M -jar minecraft_server.jar & echo $! > pid
    

    it won't let me input any text into the Minecraft server java process.

    • user1984103
      user1984103 over 10 years
      Have you tried backgrounding the process, grabbing the PID, and then bringing the process back into the foreground?
  • sean_m
    sean_m over 10 years
    Do you still need to communicate with the server process?
  • Ivan
    Ivan over 10 years
    Yes, I need to communicate with the server process (I use screen -x mc-vanilla -X stuff "say doing something blah blahboaweohv $(printf '\r')" to input things into my minecraft server.
  • Ivan
    Ivan over 10 years
    The reason I didn't want to do that was because I have multiple minecraft servers running at the same time. I wanted to get the PID of the process so I could kill that process and not the other minecraft servers.
  • sean_m
    sean_m over 10 years
    Gotcha. We use a lot of Tomcat servers at my work and use the ps aux method but use grep to parse the full path of the jar file to differentiate between server instances.
  • Mark K Cowan
    Mark K Cowan over 8 years
    Finally, I've been wondering how to run in foreground and export PID for ages!