Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use execvp()

Tags:

The user will read a line and i will retain the first word as a command for execvp.

Lets say he will type "cat file.txt" ... command will be cat . But i am not sure how to use this execvp(), i read some tutorials but still didn't get it.

#include <stdio.h> #include <stdlib.h>  int main() {     char *buf;     char command[32];     char name[32];     char *pointer;     char line[80];     printf(">");      while((buf = readline(""))!=NULL){            if (strcmp(buf,"exit")==0)         break;          if(buf[0]!=NULL)         add_history(buf);          pointer = strtok(buf, " ");         if(pointer != NULL){             strcpy(command, pointer);         }          pid_t pid;          int  status;          if ((pid = fork()) < 0) {                  printf("*** ERROR: forking child process failed\n");             exit(1);         }         else if (pid == 0) {                       if (execvp(command, buf) < 0) {                      printf("*** ERROR: exec failed\n");                 exit(1);             }         }         else                                           while (wait(&status) != pid)                    ;         free(buf);         printf(">");     }///end While     return 0; } 
like image 767
Axl Avatar asked Dec 18 '14 08:12

Axl


People also ask

How does Execvp work?

Like all of the exec functions, execvp replaces the calling process image with a new process image. This has the effect of running a new program with the process ID of the calling process. Note that a new process is not started; the new process image simply overlays the original process image.

What does Execvp return in C?

execvp() returns a negative value if the execution fails (e.g., the request file does not exist). The following is an example (in file shell. c).

Does Execvp call exit?

Once you call execvp the child process dies (for all practical purposes) and is replaced by the exec 'd process. The only way you can reach exit(0) there is if execvp itself fails, but then the failure isn't because the new program ended.

What is the return value of Execvp?

A successful call to execvp does not have a return value because the new process image overlays the calling process image. However, a -1 is returned if the call to execvp is unsuccessful.


1 Answers

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls"; char *argv[3]; argv[0] = "ls"; argv[1] = "-la"; argv[2] = NULL;  execvp(cmd, argv); //This will run "ls -la" as if it were a command 
like image 144
Ricky Mutschlechner Avatar answered Sep 24 '22 18:09

Ricky Mutschlechner