电脑技术学习

如何快速杀死占用过多资源(CPU,内存)的数据库进程

dn001

很多时候由于异常或程序错误会导致个别进程占用大量系统资源,需要结束这些进程,通常可以使用以下命令Kill进程:
alter system kill session 'sid,serial#';

但是此命令释放资源极为缓慢,具体可以参考:Oracle中Kill session的研究.
为了更快速的释放资源,通常我们使用如下步骤来Kill进程:
1.首先在操作系统级kill进程
2.在数据库内部kill session
这样通常可以快速中止进程,释放资源。

今天就遇到这样一个案例,其他朋友在数据库里kill session,可是长时间仍无效果:
[oracle@danaly ~]$ sqlplus "/ as sysdba"

SQL*Plus: Release 10.2.0.1.0 - Production on Thu Oct 27 11:09:50 2005

Copyright (c) 1982, 2005, Oracle.; All rights reserved.


Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, Oracle Label Security, OLAP and Data Mining Scoring Engine options

SQL> select sid,username,status from v$session;

SID USERNAME;;;;STATUS
---------- ------------------------------ --------
....
154 SCOTT; KILLED
...

30 rows selected.

那按照我前面提到的步骤,首先查询得到该session对应的OS进程号:
SQL> select 'kill -9 '||spid from v$process where addr = (select paddr from v$session where sid=&sid);
Enter value for sid: 154
old1: select 'kill -9 '||spid from v$process where addr = (select paddr from v$session where sid=&sid)
new1: select 'kill -9 '||spid from v$process where addr = (select paddr from v$session where sid=154)

'KILL-9'||SPID
--------------------
kill -9 22702

SQL> !

在操作系统级kill该进程:
[oracle@danaly ~]$ ps -ef|grep 22702
oracle22702;;1; 0 Oct25 ?;;;;;00:00:02 oracledanaly (LOCAL=NO)
oracle12082 12063; 0 11:12 pts/1;00:00:00 grep 22702
[oracle@danaly ~]$ kill -9 22702
[oracle@danaly ~]$ ps -ef|grep 22702
oracle12088 12063; 0 11:12 pts/1;00:00:00 grep 22702
[oracle@danaly ~]$ exit
exit

SQL> select sid,username,status from v$session;

SID USERNAME;;;;STATUS
---------- ------------------------------ --------
...
154 SCOTT; KILLED
...

30 rows selected.

SQL> select sid,serial#,username from v$session where sid=154;

SID;SERIAL# USERNAME
---------- ---------- ------------------------------
154;;;56090 SCOTT

再次在数据库中kill该session,并指定immediate选项:
SQL> alter system kill session '154,56090' immediate;

System altered.

SQL> select sid,serial#,username from v$session where sid=154;

no rows selected


此时该进程被迅速清除。