/*
* The task state array is a strange "bitmap" of
* reasons to sleep. Thus "running" is zero, and
* you can test for combinations of others with
* simple bit tests.
*/
static const char * const task_state_array[] = {
"R (running)", /* 0 */
"S (sleeping)", /* 1 */
"D (disk sleep)", /* 2 */
"T (stopped)", /* 4 */
"t (tracing stop)", /* 8 */
"X (dead)", /* 16 */
"Z (zombie)", /* 32 */
};提问:为什么要有进程状态呢? 回答:在日常生活中,可能你感冒了,你会对室友说,我今天状态不好就不去上课了。这里的状态就决定了你的后续动作——不去上课了。在Linux中也是如此,Linux可能存在很多的进程,操作系统要根据它们的状态来决定后续对这些进程的操作。
进程的状态,通俗的来讲有5种:创建状态、就绪状态、堵塞状态、执行状态、终止状态。 最基本的状态就是:运行状态、就绪状态、堵塞状态。
上面的状态好像和前面我们所写的状态不太一样啊,确实,在前面我们所写为的为进程具体的状态,相当于通俗状态的具体实例。 再来看看代码:
/*
* The task state array is a strange "bitmap" of
* reasons to sleep. Thus "running" is zero, and
* you can test for combinations of others with
* simple bit tests.
*/
static const char * const task_state_array[] = {
"R (running)", /* 0 */
"S (sleeping)", /* 1 */
"D (disk sleep)", /* 2 */
"T (stopped)", /* 4 */
"t (tracing stop)", /* 8 */
"X (dead)", /* 16 */
"Z (zombie)", /* 32 */
};ps aux / ps axj 命令有什么区别呢? aux,axj其实是分开看的:a-u-x-j
也就是说,ps aux就是以用户为主打印所有进程。ps axj打印所有进程并显示pid、ppid。 先写一个程序让它跑起来,然后观察它的状态。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
while(1)
{
printf("I am a process!\n");
sleep(1);//休眠一秒
}
return 0;
}makefile的配置:
mybin:test1.c
gcc -o mybin test1.c
.PHONY:clean
clean:
rm -f mybin把xshell开个双窗口,来观察进程的状态,一个用来运行程序,一个用来观察状态。

在此之前,我们还要在写一个循环擦查看进程状态的指令。

while :;do ps ajx|head -1 && ps ajx|grep mybin|grep -v grep;sleep 1; done每秒打印一次mybin进程的状态。下面让我们运行一下程序来看看吧。

从该程序我们可以看出该进程的各个信息,其中有个信息是有关进程状态的。就是STAT。
可是在上面的图片中为什么我们进程显示的状态是S呢?S可是睡眠的意思啊。令人费解,程序不是正在运行吗?其实图片没有错的,在我们的程序中存在一个sleep函数会让程序休眠一秒钟,进程不能在它睡眠期间还把它放在运行状态,这也就是导致了,mybin的运行状态只有一瞬间,运气好的话可能能捕捉到这一瞬间。
那么思考一下,如果把sleep去掉,STAT会是什么状态呢?
答案还是S,这是因为cout的缘故,printf也会存在休眠时间的,CPU的速度是非常快的,printf的休眠时间对于CPU的速度来说就显得非常漫长了,所以STAT依旧会显示S。
那么如何才能显示R呢?把printf去掉就可以,直接让程序执行死循环。

就是如此。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
int a = 0;
while(1)
{
scanf("%d",&a);
}
return 0;
}Z(zombie)-僵尸进程
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t id = fork();
if(id<0)
{
//程序出错
perror("fork");
return 1;
}
else if(id > 0)
{
printf("parent[%d] is sleeping...\n",getpid());
sleep(30);
}
else
{
printf("child[%d] is begin Z...\n",getpid());
sleep(5);
exit(-1);
}
return 0;
}
僵尸进程的危害
孤儿进程
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t id = fork();
if(id<0)
{
//程序出错
perror("fork");
return 1;
}
else if(id > 0)
{
printf("parent[%d] is sleeping...\n",getpid());
sleep(3);
exit(-1);
}
else
{
printf("child[%d] is begin Z...\n",getpid());
sleep(10);
}
return 0;
}
可以看到,子进程被1号进程接管了。