#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
// 创建子进程
pid = fork();
if (pid < 0) {
// 创建失败
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
// 子进程
printf("Child process: PID = %d\n", getpid());
// 执行一个简单的命令,例如 ls
execlp("/bin/ls", "ls", NULL);
// 如果 execlp 返回,说明执行失败
perror("execlp failed");
return 1;
} else {
// 父进程
printf("Parent process: PID = %d, Child PID = %d\n", getpid(), pid);
// 等待子进程结束
waitpid(pid, &status, 0);
printf("Child process exited with status %d\n", WEXITSTATUS(status));
}
return 0;
}
这段代码展示了如何在 Linux 环境下使用 C 语言创建一个子进程并执行一个简单的命令(如 ls)。具体步骤如下:
stdio.h、stdlib.h、unistd.h、sys/types.h 和 sys/wait.h。fork() 函数创建一个子进程。fork() 返回值在父进程中为子进程的 PID,在子进程中为 0,如果创建失败则返回负数。execlp() 来执行 /bin/ls 命令。如果 execlp() 调用成功,则不会返回;否则会打印错误信息并退出。waitpid() 等待子进程结束,并获取子进程的退出状态。通过这段代码,你可以了解 Linux 下多进程编程的基本概念和实现方法。
上一篇:linux复制文件夹并且重命名
下一篇:linux signal
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站