查看进程运行与否、PID等信息

大家光棍节快乐哈大笑,今天跟大家分享分享查看进程运行与否、PID等信息的方法。

进入正题:

查看进程运行与否:

首先运行smartopt_my程序

[root@FriendlyARM /]# ./smartopt_my

然后运行

[root@FriendlyARM /]# ps | grep smartopt_my              
12739 root     10056 S    ./smartopt_my 
13850 root      3072 S    grep smartopt_my

这里你可以看到出现了两行,我们理想的是一行,好吧,我们继续

[root@FriendlyARM /]# ps | grep smartopt_my |grep -v grep 
12739 root     10056 S    ./smartopt_my 

现在成功了。我们现在在执行以下命令:

[root@FriendlyARM /]# echo $?
0

结果是0,说明上一句(ps | grep smartopt_my |grep -v grep )执行成功。

现在我们关闭这个程序:

[root@FriendlyARM /]# kill -9 $(ps | grep smartopt_my |grep -v grep |awk '{print $1}')

再来执行下列命令:

[root@FriendlyARM /]# echo $?
1

结果是1,说明上一句(ps | grep smartopt_my |grep -v grep )执行失败。

这个原理就是判断ps | grep smartopt_my |grep -v grep的执行结果判断程序有没有执行。(在shell脚本中特别适用)


现在我们再来看看执行ps的输出结果:

[root@FriendlyARM /]# ps
  PID USER       VSZ STAT COMMAND
    1 root      3068 S    init     
    2 root         0 SW   [kthreadd]
    3 root         0 SW   [ksoftirqd/0]
    4 root         0 SW   [events/0]
    5 root         0 SW   [khelper]
   11 root         0 SW   [async/mgr]
  209 root         0 SW   [sync_supers]
  211 root         0 SW   [bdi-default]
  213 root         0 SW   [kblockd/0]
  222 root         0 SW   [khubd]
  228 root         0 SW   [kmmcd]
  244 root         0 SW   [rpciod/0]
  251 root         0 SW   [kswapd0]
  298 root         0 SW   [aio/0]
  302 root         0 SW   [nfsiod]
  306 root         0 SW   [crypto/0]
  417 root         0 SW   [mtdblockd]
  639 root         0 SW   [usbhid_resumer]
  687 root      3068 S    syslogd 
  690 root      3388 S    /usr/sbin/inetd 
  699 root      3068 S    init     
  700 root      3068 S    init     
  701 root      3068 S    init     
  705 root      3068 S    init     
  710 root      3076 S    /usr/sbin/telnetd -i 
  711 root      3392 S    -sh 
 3538 root      3076 S    /usr/sbin/telnetd -i 
 3539 root      3392 S    -sh 
 3665 root      3076 S    /usr/sbin/telnetd -i 
 3666 root      3392 S    -sh 
12739 root     10056 S    ./smartopt_my 
16360 root         0 SW   [flush-31:0]
16969 root      3392 R    ps 
[root@FriendlyARM /]# 

现在我要知道smartopt_my 的PID 、用户名、VSZ、STAT和COMMAND。大家有什么想法儿呢?

呵呵,我先来讲讲我的想法儿:

ps | grep smartopt_my |grep -v grep |awk '{print $1}'  得到的是PID

现在来解释一下:

ps:不用说了,查看进程(如果在PC下用ps aux);

grep smartopt_my:在ps的输出结果中过滤掉不含smartopt_my的字段;

grep -v grep:从ps | grep smartopt_my的输出结果中过滤掉含有grep的字段;

awk '{print $1}' :打印上面命令输出的一行中的第一个位置变量的结果。(注意或括号后面或前面大家不要看成是单引号,那是命令解释符,就是ESC键);


你可能感兴趣的:(shell,pid,查看进程运行与否)