Q:

How to kill an execvp process

In a C program, I am using execvp() to create a netcat listener. When the program terminates, I would like to kill the listener. For example:
int main(){
  char *listener[] = {
    "/bin/bash",
    "-c",
    "nc -l 1338 > text.tar",
     NULL
   };
   execvp(listener[0], listener);
   return 0;
}

I would like to kill this netcat process right before the program terminates. However, I am looking at this code and thinking that maybe the program will terminate before the netcat listener receives any data. Maybe I could issue a wait command.
I guess it boils down to two questions:

How can I kill the execvp proccess?
Do I need a wait() call to give netcat some time?

A:

The exec functions family only returns when there is an error (i.e. the program could not be executed).
So you have to fork() first and keep track of the pid. But if you want to kill the child process just before the main program ends, it will likely have  no time to do anything.
Here we give 10 seconds to the child process before killing it
#include <sys/types.h>
#include <signal.h>

#define TIME 10

int main(){
  char *listener[] = {
    "/bin/bash",
    "-c",
    "nc -l 1338 > text.tar",
     NULL
   };
   pid_t pid = fork();
   if ( ! pid) { // child
      execvp(listener[0], listener);
      // doesn't return (check error maybe)
   }
   printf("Waiting for %d seconds...\n", TIME);
   sleep(TIME);
   kill(pid, SIGTERM); 
   return 0;
}

The SIGTERM signal is used (or use SIGINT, like Control-C), check the man page to choose another one if necessary. SIGKILL is the "strongest" (not catchable by the child).

