kill a process started with popen

前端 未结 8 1341
温柔的废话
温柔的废话 2020-12-04 15:04

After opening a pipe to a process with popen, is there a way to kill the process that has been started? (Using pclose is not what I want because th

8条回答
  •  [愿得一人]
    2020-12-04 15:35

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

提交回复
热议问题