Linux基础知识系列之进程和端口

579 阅读2分钟

进程

查看进程是工作中使用频率较高的需求,一般来说使用的就是ps -ef | grep xxx,执行之后就是如下:

[root@hadoop001 ~]# ps -ef | grep tail 
root      9831  9779  0 22:10 pts/1    00:00:00 tail -f tail.log
root      9893  8818  0 22:11 pts/0    00:00:00 grep --color=auto tail
进程用户   pid  父pid                            进程内容

#返回结果不带grep
[root@hadoop001 ~]# ps -ef | grep tail | grep -v grep
root      9831  9779  0 22:10 pts/1    00:00:00 tail -f tail.log

一般kill命令与此相搭配,kill -9 pid 杀死pid的进程。不过生产上执行该命令之前,一定要确认清楚:

  1. 该进程是否真的杀?
  2. 杀的进程是否你想要杀?

这里也提供批量杀进程,kill -9 $(pgrep -f xxx),杀掉与xxx相关的命令,但是这个命令也会误杀掉你不想杀掉的同名的xxx进程,不建议使用。

端口

怎么查看服务使用的端口呢?一般使用的都是netstat -nlp | grep pid,这个就可以与上面的结合使用了,下面举个例子:

# sshd服务有许多进程,主要关注pid和父pid
[root@hadoop001 ~]# ps -ef | grep sshd
root      3315     1  0 14:13 ?        00:00:00 /usr/sbin/sshd -D   <-- 主要
root      8816  3315  0 22:05 ?        00:00:00 sshd: root@pts/0
root      9776  3315  0 22:10 ?        00:00:00 sshd: root@pts/1
root      9834  3315  0 22:10 ?        00:00:00 sshd: root@pts/2
root     11499  8818  0 22:27 pts/0    00:00:00 grep --color=auto sshd

[root@hadoop001 ~]# netstat -nlp | grep 3315
tcp        0     0   0.0.0.0:22      0.0.0.0:*       LISTEN      3315/sshd           
tcp6       0     0   :::22           :::*            LISTEN      3315/sshd 

通过上述可以看出sshd服务的端口是22,而且22前面的要是机器的ip或0.0.0.0 或 :::,表示对外的任意ip可以服务,但是127.0.0.1或localhost,只能在这台的机器上访问这个服务。 所以,如果你想要看一个的服务的端口,流程就是服务名称->pid->port。