创建子进程,在子进程中使用 exec 系列函数执行“ls -l”命令,父进程等待子进程结束后输出“child over”
时间: 2024-03-08 15:49:04 浏览: 65
好的,您可以参考以下代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
pid = fork();
if (pid < 0) { // 创建子进程失败
printf("Error: failed to fork.\n");
exit(1);
} else if (pid == 0) { // 子进程
execl("/bin/ls", "ls", "-l", NULL);
exit(0);
} else { // 父进程
wait(&status); // 等待子进程结束
if (WIFEXITED(status)) { // 判断子进程是否正常结束
printf("child over\n");
} else {
printf("Error: child process terminated abnormally.\n");
}
}
return 0;
}
```
在这个程序中,我们首先调用 `fork()` 创建一个子进程,然后在子进程中调用 `execl()` 执行 `ls -l` 命令。父进程调用 `wait()` 等待子进程结束,并根据子进程的退出状态输出相应的信息。
需要注意的是,`execl()` 函数的第一个参数是要执行的命令的路径,第二个参数是命令的名称,后面的参数是命令的参数列表,最后一个参数必须是 `NULL`。在本例中,我们调用的是 `/bin/ls` 命令,因此第一个参数是 `/bin/ls`。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)