父进程从终端读取要执行的命令,并交给子进程执行。父进程等待子进程结束,并打印子进程的返回值。 提示:从终端读取要执行的命令可用fgets()实现。
时间: 2024-05-10 07:12:30 浏览: 19
父进程从终端读取要执行的命令,可以使用fgets()函数实现。之后,父进程需要调用fork()函数创建一个子进程,并将读取到的命令传递给子进程执行。父进程需要使用wait()函数等待子进程执行完毕,并获取子进程的返回值,最后打印出来。
以下是代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
char command[1024];
int status;
pid_t pid;
printf("请输入要执行的命令:");
fgets(command, sizeof(command), stdin);
pid = fork();
if (pid == -1) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid == 0) { // 子进程
system(command);
exit(EXIT_SUCCESS);
} else { // 父进程
wait(&status);
printf("子进程返回值:%d\n", WEXITSTATUS(status));
}
return 0;
}
```
相关问题
父进程从终端读取要执行的命令,并交给子进程执行。父进程等待子进程结束,并打印子进程的返回值。
可以使用`fork()`和`execvp()`系统调用来创建子进程并执行命令,使用`wait()`系统调用来等待子进程结束并获取返回值。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
char command[100];
// 从终端读取要执行的命令
printf("请输入要执行的命令:");
fgets(command, sizeof(command), stdin);
// 创建子进程
pid_t pid = fork();
if (pid == -1) {
perror("fork error");
exit(1);
} else if (pid == 0) {
// 子进程执行命令
char* args[] = {"sh", "-c", command, NULL};
execvp(args[0], args);
perror("execvp error");
exit(1);
} else {
// 等待子进程结束,并打印返回值
int status;
wait(&status);
if (WIFEXITED(status)) {
printf("子进程返回值:%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("子进程被信号终止\n");
}
}
return 0;
}
```
注意,这里使用了`sh -c`来执行命令,因为`execvp()`需要传入命令及其参数的数组,而命令本身和参数可能是不确定的,使用`sh -c`可以将命令及其参数作为一个字符串传入。
父进程从终端读取要执行的命令,并交给子进程执行。父进程等待子进程结束,并打印
子进程的退出状态。可以使用C语言中的fork()函数来创建子进程,使用exec()函数族来执行命令,使用waitpid()函数来等待子进程结束并获取其退出状态。
以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
char cmd[100];
pid_t pid;
int status;
while (1) {
printf("Enter command: ");
fgets(cmd, sizeof(cmd), stdin);
if (cmd[0] == '\n') {
break;
}
pid = fork();
if (pid < 0) {
perror("fork error");
exit(1);
} else if (pid == 0) {
// child process
execl("/bin/sh", "sh", "-c", cmd, NULL);
perror("execl error");
exit(1);
} else {
// parent process
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child process exited with status %d\n", WEXITSTATUS(status));
} else {
printf("Child process exited abnormally\n");
}
}
}
return 0;
}
```
该程序会不断从终端读取命令,创建子进程执行命令,等待子进程结束并打印退出状态。输入空行会结束程序。注意,在使用execl()函数族执行命令时,需要把命令字符串传递给/bin/sh解释器来执行。