tarun14110
tarun14110

Reputation: 990

how to store execvp result in a char array as a string

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.

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); 
          }
}

Upvotes: 0

Views: 1010

Answers (1)

P.P
P.P

Reputation: 121407

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).

   #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.

Upvotes: 2

Related Questions