这是我编写的示例程序,用于理解终端中的执行工作 program1.c
#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
int main()
{
int i;
printf("Checking out linux working details 2\n");
pid_t pid=fork();
return 0;
}
现在请您解释一下bash,ps,sh进程的状态(即他们的pid等)。这是样本运行
运行:
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4496 4488 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4506 4496 0 80 0 - 3561 - pts/2 00:00:00 ps
$ gcc program1.c
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4496 4488 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4513 4496 0 80 0 - 3561 - pts/2 00:00:00 ps
$ ./a.out
Checking out linux working details 2
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4496 4488 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4516 4496 0 80 0 - 3561 - pts/2 00:00:00 ps
$ ./a.out
Checking out linux working details 2
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4496 4488 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4519 4496 0 80 0 - 3561 - pts/2 00:00:00 ps
program2.c
#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
int main()
{
system("ps -l");
return 0;
}
示例运行:
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4592 4584 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4602 4592 0 80 0 - 3561 - pts/2 00:00:00 ps
$ gcc program2.c
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4592 4584 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4609 4592 0 80 0 - 3561 - pts/2 00:00:00 ps
$ ./a.out
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4592 4584 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 S 1000 4610 4592 0 80 0 - 1055 wait pts/2 00:00:00 a.out
0 S 1000 4611 4610 0 80 0 - 1119 wait pts/2 00:00:00 sh
0 R 1000 4612 4611 0 80 0 - 3561 - pts/2 00:00:00 ps
$ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 4592 4584 0 80 0 - 6730 wait pts/2 00:00:00 bash
0 R 1000 4613 4592 0 80 0 - 3561 - pts/2 00:00:00 ps
ps:非常感谢详细的答案
答案 0 :(得分:0)
每次运行程序时,都会创建一个具有唯一pid的新进程。 这就是为什么在你的例子中bash的pid始终保持不变的原因,因为它仍然是相同的过程,并且ps的所有连续调用都有不同的。
你虽然可以看到父pid(ppid)与&#34; ps -l&#34;它显示了创建它的进程的pid(分叉)。
也许您想尝试以下代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
int i;
printf("before fork() ps -l\n");
system("ps -l");
pid_t pid=fork();
if (pid < 0) {
printf("fork-error.");
} else if (pid == 0) {
printf("child ps -l\n");
system("ps -l");
} else {
int status;
pid_t finished = wait(&status);
printf("parent with child %i finished %i ps -l\n", pid, finished);
system("ps -l");
}
return 0;
}