D状态总结

在工作中,由vim打开文件并修改文件但无法关闭文件的问题引出的D状态问题。

D状态即无法中断的休眠进程,是由于在等待IO,比如磁盘IO,网络IO,其他外设IO,如果进程正在等待的IO在较长的时间内都没有响应,那么就被ps看到了,同时也就意味着很有可能有IO出了问题,可能是外设本身出了故障,也可能是比如挂载的远程文件系统已经不可访问等操作时出现的问题。

而task_uninterruptible状态存在的意义就在于,内核的某些处理流程是不能被打断的。如果响应异步信号,程序的执行流程中就会被插入一段用于处理异步信号的流程(这个插入的流程可能只存在于内核态,也可能延伸到用户态),于是原有的流程就被中断了。

在进程对某些硬件进行操作时(比如进程调用read系统调用对某个设备文件进行读操作,而read系统调用最终执行到对应设备驱动的代码,并与对应的物理设备进行交互),可能需要使用task_uninterruptible状态对进程进行保护,以避免进程与设备交互的过程被打断,造成设备陷入不可控的状态。这种情况下的task_uninterruptible状态总是非常短暂的,通过ps命令基本上不可能捕捉到。

我们通过vmstat 命令中procs下的b 可以来查看是否有处于uninterruptible 状态的进程。 该命令只能显示数量。

In computer operating systems terminology, a sleeping process can either be interruptible (woken via signals) or uninterruptible (woken explicitly). An uninterruptible sleep state is a sleep state that cannot handle a signal (such as waiting for disk or network IO (input/output)).

When the process is sleeping uninterruptibly, the signal will be noticed when the process returns from the system call or trap.

-- 这句是关键。 当处于uninterruptibly sleep 状态时,只有当进程从system 调用返回时,才通知signal。

A process which ends up in “D” state for any measurable length of time is trapped in the midst of a system call (usually an I/O operation on a device — thus the initial in the ps output).

Such a process cannot be killed — it would risk leaving the kernel in an inconsistent state, leading to a panic. In general you can consider this to be a bug in the device driver that the process is accessing.

 

引起D状态的根本原因是由于IO等待,若你对某个磁盘的IO操作特别频繁,就会造成后续的IO操作处于等待状态,即处于D状态。此时,你可以使用iostat命令查看当前操作的磁盘的IO是否达到瓶颈值,若达到可以从用户层面入手调整IO操作。