I need some help writing a command that will be put into a .sh. I want to return the process id, which in the output below is 3678, but I'm having diffuclty because the process id changes everytime it gets restarted, so my code breaks
Output:
[root@server1 /usr/home/aaron]# ps -xauww | grep java | grep www
www 3678 0.0 3.2 1308176 267864 ?? Is 3:21PM 0:17.19 [开发者_开发问答java]
[root@server1 /usr/home/aaron]#
Heres what I was doing until I realized the column changed when the pid changed:
ps -xauww | grep java | grep www | cut -d" " -f6
Any help is appreciated. thanks.
If the starting is automated by a shell script, you can write the pid of the just-started-process which is in the variable $!
.
java ...... &
echo "$!" > myjavaprogram.pid
When you need to kill it, just do:
kill `cat myjavaprogram.pid`
Below pgrep
command works for getting pid by jar-file name:
pgrep -f test-app.jar
As per http://cfajohnson.com/shell/cus-faq-2.html
How do I get a process id given a process name? Or, how do I find out if a process is still running, given a process ID?
There isn't a reliable way to to this portably in the shell. Some systems reuse process ids much like file descriptors. That is, they use the lowest numbered pid which is not currently in use when starting a new process. That means that the pid you're looking for is there, but might not refer to the process you think it does.
The usual approach is to parse the output of ps, but that involves a race condition, since the pid you find that way may not refer to the same process when you actually do something with that pid. There's no good way around that in a shell script though, so be advised that you might be stepping into a trap.
One suggestion is to use pgrep if on Solaris, and 'ps h -o pid -C $STRING' if not, and your ps supports that syntax, but neither of those are perfect or ubiquitous.
The normal solution when writing C programs is to create a pid file, and then lock it with fcntl(2). Then, if another program wants to know if that program is really running, it can attempt to gain a lock on the file. If the lock attempt fails, then it knows the file is still running.
We don't have options in the shell like that, unless we can supply a C program which can try the lock for the script. Even so, the race condition described above still exists.
That being said look at this: http://www.faqs.org/faqs/unix-faq/faq/part3/section-10.html it might help you out ?
One way can be found in: man pgrep
精彩评论