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

时间:2022-10-07 21:28:02

If a user types "ls" execvp displays the result of "ls" to the screen. I would like to store this in a char array as a string. Can anyone help me? THanks in advance.

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

1 个解决方案

#1


2  

popen() is more appropriate for your purpose than execvp() since you want to read the output from the exec'ed command (See the linked manual for an example).

popen()比execvp()更适合你的目的,因为你想从exec'ed命令读取输出(参见链接手册中的一个例子)。

   #include <stdio.h>

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

   int pclose(FILE *stream);

popen() returns FILE * using which you can read the output returned by the command.

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

#1


2  

popen() is more appropriate for your purpose than execvp() since you want to read the output from the exec'ed command (See the linked manual for an example).

popen()比execvp()更适合你的目的,因为你想从exec'ed命令读取输出(参见链接手册中的一个例子)。

   #include <stdio.h>

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

   int pclose(FILE *stream);

popen() returns FILE * using which you can read the output returned by the command.

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