如果用户键入“ls”,execvp 会在屏幕上显示“ls”的结果。我想将其作为字符串存储在 char 数组中。谁能帮我? 提前致谢。
int main () {
char response[1000];
char *buffer[100];
int pid, status;
printf("Please enter the shell command: ");
scanf("%s",&response);
pid = fork();
if (pid < 0) {
printf("Unable to create child process, exiting.\n");
exit(0);
}
if (pid == 0) {
printf("I'm the child.\n");
*buffer = response;
execvp(*buffer,buffer);
printf("execvp failed\n");
}
else{
wait(&status);
exit(0);
}
}
最佳答案
popen()
比 execvp()
更适合您的目的,因为您想读取执行命令的输出(有关示例,请参见链接的手册)。
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen()
返回 FILE *
,您可以使用它读取命令返回的输出。
关于c - 如何将 execvp 结果作为字符串存储在 char 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32505718/