sleep(0)也会让程序进入sleep状态,为何?
我写了一个很小的程序a.cpp:
#include
#include
#include
int main(void)
{
for(;;)
{
sleep(0);
printf("haha%d\n",++i);
}
return 0;
}
编译运行这个程序,我进入/proc文件系统查看:
[a@localhost 2857]$ ps -ef|grep a.out
a 2899 2695 16 09:29 pts/0 00:00:01 ./a.out
a 2901 2727 1 09:29 pts/1 00:00:00 grep a.out
[a@localhost 2857]$ cd /proc/2899
[a@localhost 2899]$ cat status|grep State
State:S (sleeping)
[a@localhost 2899]$ cat status|grep State
State:S (sleeping)
[a@localhost 2899]$ cat status|grep State
State:R (running)
[a@localhost 2899]$ cat status|grep State
State:S (sleeping)
[a@localhost 2899]$ cat status|grep State
State:R (running)
[a@localhost 2899]$ cat status|grep State
State:S (sleeping)
看起来,这个程序不断地在Running状态和Sleep状态之间切换。所以我有两个问题:
(1) sleep(0)也会让程序sleep?
(2) 我的linux环境是在一台虚拟机当中运行的。这个虚拟机只分配了一个cpu。网上说,如果系统里面只有一个cpu的话,那么只能有一个进程处于Running状态----那么既然命令行当中cat status|grep State在运行,是不是a.out程序就不可能处于运行状态。或者说,要查看/proc下面的State,就只能返回非Running的状态?(因为grep在运行)
但是实际显示出来的结果,和我在第(2)点当中的预测又非常的不一样。这是为什么呢?
------解决思路----------------------
引用:Quote: 引用:(1)我的理解:
sleep如何实现:sleep应该是启动一个定时器,通过回调函数判断 定时器的时间是否已经到达。这样,即使sleep(0),也应该启动一个等待时间为0的定时器。 然后回调发现消逝的时间已经超过0s,立即跳出sleep。
也就是说,sleep(0)并不是真的不sleep了,它只是睡眠了执行一个回调函数的时间。
而/proc的内容应该是在执行回调函数时写入的。
(2)cat status
------解决思路----------------------
grep State为Running并不是指这个进程当前时刻真的在运行,而是说它出于一个运行态或者就绪态。这是相对等待态/睡眠态/阻塞态而言。。。。是万事俱备,之前cpu的状态。
在status文件中区分运行态和就绪态是没有意义的。因为,可能你在写入status的这个过程中就调用了其它进程(写进程)。
你的意思是说,Running可以是执行态或者就绪态,或者说,这里的State不会显示诸如"Ready"之类的信息?
关于state显示的状态,可以直接查阅man手册 : man proc
state %c One character from the string "RSDZTW" where R is
running, S is sleeping in an interruptible wait, D
is waiting in uninterruptible disk sleep, Z is zom‐
bie, T is traced or stopped (on a signal), and W is
paging.