Debian进程的生命周期可以分为以下几个阶段:
fork()系统调用创建一个子进程。子进程是父进程的一个副本,拥有相同的代码、数据段和堆栈。exec()系列函数(如execl(), execp(), execv()等)来替换其内存空间,加载并执行一个新的程序。exit()或_exit()函数正常退出。SIGKILL)而异常终止。wait()或waitpid()来回收资源。wait()或waitpid()来回收子进程的资源。以下是一个简单的示例,展示了如何创建一个子进程并等待其结束:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
// Fork失败
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
printf("Child process: PID = %d\n", getpid());
// 子进程执行的任务
exit(EXIT_SUCCESS);
} else {
// 父进程
int status;
printf("Parent process: PID = %d, Child PID = %d\n", getpid(), pid);
// 等待子进程结束
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
}
}
return 0;
}
这个示例展示了如何使用fork()创建子进程,并使用waitpid()等待子进程结束并回收其资源。