在 Linux 中,进程创建和管理的相关函数主要是 fork()
、exec()
、wait()
和 exit()
举个例子:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h>int main() {pid_t pid;// 创建子进程pid = fork();if (pid < 0) {// 出错处理perror("fork failed");exit(EXIT_FAILURE);} else if (pid == 0) {// 子进程代码printf("Child process with PID: %d\n", getpid());// 替换当前进程的代码段execlp("/bin/ls", "ls", NULL);// 如果 execlp() 失败,则会执行以下代码perror("execlp failed");exit(EXIT_FAILURE);} else {// 父进程代码printf("Parent process with PID: %d\n", getpid());// 等待子进程结束 wait(NULL);printf("Child process terminated\n");}// 退出当前进程printf("Exiting...\n");exit(EXIT_SUCCESS); }
执行结果如下: