编写程序mysh.c,在其主函数中读取“命令字符串”(由第二个参数开始的所有命令行参数构成),在程序中创建一个子进程,然后在子进程中调用exec执行该命令字符串。如:用户输入“mysh ls -l”,则在子进程中执行“ls -l命令”。最后,父进程等待子进程执行完毕后以子进程的退出状态退出。
时间: 2024-03-25 09:40:12 浏览: 136
好的,根据您的要求,我来给您编写一个符合要求的mysh.c程序。
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
pid_t pid;
int status;
if (argc < 2) {
fprintf(stderr, "Usage: %s command [args ...]\n", argv[0]);
exit(1);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) { // child process
if (execvp(argv[1], &argv[1]) < 0) {
perror("execvp");
exit(1);
}
} else { // parent process
if (waitpid(pid, &status, 0) < 0) {
perror("waitpid");
exit(1);
}
if (WIFEXITED(status)) {
printf("Child process exited with status %d\n", WEXITSTATUS(status));
}
}
return 0;
}
```
这个程序通过 `fork` 创建了一个子进程,然后在子进程中调用 `execvp` 执行命令字符串。在父进程中,使用 `waitpid` 等待子进程执行完毕,并获取子进程的退出状态。最后,将子进程的退出状态输出到标准输出。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)