Find the pid of a java process under Linux

前端 未结 5 958
一生所求
一生所求 2020-12-30 00:37

I have a Java program running on a Linux computer, and want to find the process ID (pid) of its process. I know the ps command can provide this information, but

5条回答
  •  有刺的猬
    2020-12-30 01:15

    using ps

    ps allows the user to define his own formatting for its output with the -o switch, and -C to select entries by the given command. I would go with:

    ps -C java -o pid
    

    from the man page:

       -C cmdlist      Select by command name
                       This selects the processes whose executable name is given in cmdlist.
    
       -o format       user-defined format.
                       format is a single argument in the form of a blank-separated or comma-separated list, which offers a way to specify
                       individual output columns. The recognized keywords are described in the STANDARD FORMAT SPECIFIERS section below. Headers
                       may be renamed (ps -o pid,ruser=RealUser -o comm=Command) as desired. If all column headers are empty
                       (ps -o pid= -o comm=) then the header line will not be output. Column width will increase as needed for wide headers; this
                       may be used to widen up columns such as WCHAN (ps -o pid,wchan=WIDE-WCHAN-COLUMN -o comm). Explicit width control
                       (ps opid,wchan:42,cmd) is offered too. The behavior of ps -o pid=X,comm=Y varies with personality; output may be one
                       column named "X,comm=Y" or two columns named "X" and "Y". Use multiple -o options when in doubt. Use the PS_FORMAT
                       environment variable to specify a default as desired; DefSysV and DefBSD are macros that may be used to choose the default
                       UNIX or BSD columns.
    

    One can get more accurate results by specifying more restrictions (ie the user under which the process runs, etc). Look at the man page for more information and other switches.

    example:

    $ sleep 10 &
    [1] 12654
    $ ps -C sleep -o pid
    12654
    

    using the shell

    I don't know why you use an .sh script to run your code and not call java directly, but if in any case you use the & (background) operator, you can grab the pid through your shell, with the $! variable.

    for example:

    $ sleep 5 &
    [1] 12395
    $ echo $!
    12395
    

    same goes for the java -jar .. & command, $! will be set to the pid of the last backgrounded job.

提交回复
热议问题