【问题标题】:how to store execvp result in a char array as a string如何将 execvp 结果作为字符串存储在 char 数组中
【发布时间】:2015-12-06 23:12:50
【问题描述】:

如果用户键入“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); 
          }
}

【问题讨论】:

  • 看看pipe()dup2()
  • 你能提供一个好的链接来阅读吗?我在谷歌上搜索了一个多小时,越来越困惑。

标签: c linux shell exec execvp


【解决方案1】:

popen()execvp() 更适合您的目的,因为您想读取 exec'ed 命令的输出(有关示例,请参阅链接的手册)。

   #include <stdio.h>

   FILE *popen(const char *command, const char *type);

   int pclose(FILE *stream);

popen() 返回FILE *,您可以使用它读取命令返回的输出。

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 2012-02-28
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    相关资源
    最近更新 更多