Linux进程

分别用fork、vfork创建进程

  • 使用fork创建进程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# include<stdio.h>
# include<unistd.h>
# include<stdlib.h>
# include<sys/types.h>

int main()
{
pid_t childpid;
int status;
childpid = fork();
if (childpid == -1)
{
printf("Creating Error\n");
exit(-1);
}
else if (childpid ==0 )
{
printf("In child process\n");
sleep (3);
printf("/tchild pid = %d\n",getpid());
printf("\tchild ppid =%d\n",getppid());
exit(1);
}
else
{
waitpid(childpid,&status,0);
printf("In parent\n");
printf("\tparent pid = %d\n",getpid());
printf("\tparent ppid = %d\n",getppid());
printf("\tchild process exited with status %d\n",status);
}
exit (1);
}

52254964477

  • 使用vfork创建进程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# include<stdio.h>
# include<unistd.h>
# include<stdlib.h>
# include<sys/types.h>

int main()
{
pid_t childpid;
int status;
childpid = vfork();
if (childpid == -1)
{
printf("Creating Error\n");
exit(-1);
}
else if (childpid ==0 )
{
printf("In child process\n");
sleep (3);
printf("/tchild pid = %d\n",getpid());
printf("\tchild ppid =%d\n",getppid());
exit(1);
}
else
{
waitpid(childpid,&status,0);
printf("In parent\n");
printf("\tparent pid = %d\n",getpid());
printf("\tparent ppid = %d\n",getppid());
printf("\tchild process exited with status %d\n",status);
}
exit (1);
}

52255002942

显示进程的相关信息

  • ps -l:仅查看自己的bash相关进程

    F:进程标志

    ​ 4:表示权限为root

    ​ 1:表示只能复制,不能执行

    S:表示进程的状态(STAT)

    ​ R:running表示正在运行状态

    ​ S:sleep表示沉睡状态,但是可以唤醒

    ​ D:表示沉睡状态,不能唤醒,通常这个进程可能在等待I/O的情况

    ​ T:stop表示停在状态,例如暂停的后台工作或出错进程

    ​ Z:僵尸进程,进程已经终止但不能提出内存外

    UID/PID/PPID:表示用户的UID/进程的PID号码/此进程的父进程PID号码

    C:表示CPU的使用率,单位是百分比

    PRI/NI:表示此进程被CPU执行的优先级,数字越小,优先级越高

    ADDR:支持该进程在内存的那个部分,若该进程正在运行这表示为“-”

    SZ:表示该进程占用了多少内存

    WCHAN:表示该进程是否运行,若在运行这表示为“-”

    TTY:表示登陆终端,若是远程登陆表示为pts/h

    TIME:表示该进程使用CPU的时间

    CMD:command,表示那个命令启动的该进程

52255180197

  • ps -aux 查看系统所有进程

    USER:表示该进程所属用户

    PID:该进程的PID号

    %CPU:表示该进程的CPU占用率

    %MEM:表示该进程的物理内存占用率

    VSZ:表示该进程占用了多少虚拟内存量

    RSS:表示该进程占用了多少固定内存量

    TTY:表示登陆端口

    STAT:和上面介绍的进程状态一样(R/S/D/T/Z进程)

    START:该进程触发启动的时间

    TIME:表示该进程占用CPU的时间

    COMMAND:表示触动该进程的命令

52255168294

从当前进程找到init的路线(进程号)

  • 使用ps查看当前进程,以bash进程为例,使用ps -ef|grep[ppid]

52255073365

52255079594

路径为2452、2445、1711、1541、945、1。

Donate comment here