2

I am trying to execute a command using execv. After running this program, I can see the statement "Going to call execv!" being printed on the standard output.

I can also see the prints from the program "leaky". Actually everything is working as expected except that I can't see print statements in the if or else block i.e. neither "execv failed! error: " nor "Successfully executed valgrind!" is being printed on the output.

Am I missing some obvious point here about execv?

#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>

int main()
{
   char *args[5] = {"/usr/bin/valgrind", "--leak-check=full", "--log-file=valgrindReport.txt", "./leaky", NULL};
   printf("Going to call execv!\n");
   if(execv("/usr/bin/valgrind", args) < 0)
   {
      printf("execv failed! error: %s\n", strerror(errno));
      return 0;
   }
   else
   {
      printf("Successfully executed valgrind!\n");
   }
   return 0;
}
Zumo de Vidrio
  • 2,021
  • 2
  • 15
  • 33
aniztar
  • 45
  • 4
  • 6
    Reading the [man page](https://linux.die.net/man/3/execv) will help you: "The exec() family of functions **replaces** the current process image" and "The exec() functions only return if an error has occurred." – kaylum Feb 07 '17 at 05:21
  • If `execv` succeeds in running the program, the caller process is kind of "replaced" by the new program. So it's not "call program and get result", use `system` function for that. – yeputons Feb 07 '17 at 05:24
  • Possible duplicate of [Does the C execv() function terminate the child proccess?](http://stackoverflow.com/questions/5172257/does-the-c-execv-function-terminate-the-child-proccess) – Thomas Padron-McCarthy Feb 07 '17 at 11:19

1 Answers1

5

If you get the output of valgrind then obviously execve was successful. If execve is successful it replaces the current process image with the one to be started and does not return. If execve returns then it failed.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69