c00kiemon5te..
24
运用 ps
ps允许用户使用-o开关为其输出定义自己的格式,并-C通过给定命令选择条目.我会选择:
ps -C java -o pid
从手册页:
-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.
通过指定更多限制(即运行进程的用户等),可以获得更准确的结果.查看手册页以获取更多信息和其他开关.
例:
$ sleep 10 &
[1] 12654
$ ps -C sleep -o pid
12654
使用shell
我不知道为什么你使用.sh脚本来运行你的代码而不是java直接调用,但是如果在任何情况下你使用&(背景)运算符,你可以pid使用$!变量来获取shell .
例如:
$ sleep 5 &
[1] 12395
$ echo $!
12395
同样适用于该java -jar .. &命令,$!将设置为最后一个后台作业的pid.