gpt4 book ai didi

c - 如何将 execvp 结果作为字符串存储在 char 数组中

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:05 25 4
gpt4 key购买 nike

如果用户键入“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com