进程控制是操作系统中非常重要的一个功能。在Linux系统中,进程是一个非常基本的概念,每个进程都有自己的PID(进程ID)、PPID(父进程ID)、进程状态等等。
进程控制可以通过系统调用来实现。常用的有fork、exec、wait、waitpid等。
下面是一个简单的示例代码,实现了通过fork创建子进程并输出当前进程ID、父进程ID和子进程ID:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid;
printf("Parent process ID: %d\n", getpid()); // 输出父进程ID
pid = fork(); // 创建子进程
if (pid < 0) { // 创建进程失败
fprintf(stderr, "Fork failed.\n");
return 1;
} else if (pid == 0) { // 子进程
printf("Child process ID: %d\n", getpid()); // 输出子进程ID
printf("Parent process ID: %d\n", getppid()); // 输出父进程ID
} else { // 父进程
wait(NULL); // 等待子进程结束
printf("Child process finished.\n");
}
return 0;
}
运行这段代码,输出如下:
Parent process ID: 1234
Child process ID: 1235
Parent process ID: 1234
Child process finished.
可以看到,父进程ID是1234,子进程ID是1235,而在子进程中,父进程ID是1234。并且,在父进程中,使用了wait函数等待子进程结束。