如何将execvp结果作为字符串存储在字符数组中
如果用户键入“ls”,execvp将向屏幕显示“ls”的结果。我想将其作为字符串存储在char数组中。有人能帮我吗? 提前谢谢如何将execvp结果作为字符串存储在字符数组中,c,linux,shell,exec,execvp,C,Linux,Shell,Exec,Execvp,如果用户键入“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();
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);
}
}
int main(){
字符响应[1000];
字符*缓冲区[100];
int-pid,状态;
printf(“请输入shell命令:”);
scanf(“%s”,响应(&R));
pid=fork();
if(pid<0){
printf(“无法创建子进程,正在退出。\n”);
出口(0);
}
如果(pid==0){
printf(“我是孩子。\n”);
*缓冲区=响应;
execvp(*缓冲区,缓冲区);
printf(“execvp失败\n”);
}
否则{
等待(&状态);
出口(0);
}
}
比execvp()
更适合您的用途,因为您希望读取exec'ed命令的输出(请参阅链接手册中的示例)
#包括
文件*popen(const char*命令,const char*类型);
int pclose(文件*流);
popen()
返回文件*
,您可以使用该文件读取命令返回的输出。查看pipe()
和dup2()
。能否提供一个好的链接以供读取?我在谷歌上搜索了一个多小时,越来越困惑。
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);