kill a process started with popen kill a process started with popen multithreading multithreading

kill a process started with popen


Don't use popen(), write your own wrapper that does what you'd like.

It's fairly straightforward to fork(), and then replace stdin & stdoutby using dup2(), and then calling exec() on your child.

That way, your parent will have the exact child PID, and you can usekill() on that.

Google search for "popen2() implementation" for some sample code onhow to implement what popen() is doing. It's only a dozen or so lineslong. Taken from dzone.com we can seean example that looks like this:

#define READ 0#define WRITE 1pid_tpopen2(const char *command, int *infp, int *outfp){    int p_stdin[2], p_stdout[2];    pid_t pid;    if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)        return -1;    pid = fork();    if (pid < 0)        return pid;    else if (pid == 0)    {        close(p_stdin[WRITE]);        dup2(p_stdin[READ], READ);        close(p_stdout[READ]);        dup2(p_stdout[WRITE], WRITE);        execl("/bin/sh", "sh", "-c", command, NULL);        perror("execl");        exit(1);    }    if (infp == NULL)        close(p_stdin[WRITE]);    else        *infp = p_stdin[WRITE];    if (outfp == NULL)        close(p_stdout[READ]);    else        *outfp = p_stdout[READ];    return pid;}

NB: Seems like popen2() is what you want, but my distribution doesn't seem to come with this method.


Here is an improved version of popen2 (credit is due to Sergey L.). The version posted by slacy does not return the PID of the process created in popen2, but the PID assigned to sh.

pid_t popen2(const char **command, int *infp, int *outfp){    int p_stdin[2], p_stdout[2];    pid_t pid;    if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)        return -1;    pid = fork();    if (pid < 0)        return pid;    else if (pid == 0)    {        close(p_stdin[WRITE]);        dup2(p_stdin[READ], READ);        close(p_stdout[READ]);        dup2(p_stdout[WRITE], WRITE);        execvp(*command, command);        perror("execvp");        exit(1);    }    if (infp == NULL)        close(p_stdin[WRITE]);    else        *infp = p_stdin[WRITE];    if (outfp == NULL)        close(p_stdout[READ]);    else        *outfp = p_stdout[READ];    return pid;}

The new version is to be called with

char *command[] = {"program", "arg1", "arg2", ..., NULL};


popen does not actually start a thread, but rather forks a process. As I look at the definition, it doesn't look like there is an easy way to get PID of that process and kill it. There might be difficult ways like examining process tree, but i guess you'd be better off with using pipe, fork and exec functions to mimic behaviour of popen. Then you can use PID you get from fork() to kill the child process.