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

标签 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();
     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/

相关文章:

linux - 编写一个列出目录内容的脚本?

在 C 程序中更改 Linux shell 中的工作目录

bash - 如何获取给定 ip 地址的以太网端口?

c++ - 混合 C/C++ 代码产生 "undefined symbol"与共享库

c - 二维数组作为函数参数

c++ - 如何使用 NetBeans 调试不是用 NetBeans 编译的 C++ 库?

c - Valgrind:禁用条件跳转(或整个库)检查

c - Gtk3:GtkFixed 中小部件的大小

c - exit() 调用 pthread_mutex_lock()

bash - Bash 中的 while 循环子 shell 困境