且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

杀死一个进程开始的popen

更新时间:2021-10-19 02:03:49

不要使用popen()完成,并编写您自己的包装,做你喜欢什么。

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

这是相当简单到餐桌(),然后替换标准输入和放大器;标准输出
在您的孩子使用dup2(),然后调用exec()

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

这样,你的父母将有确切的孩子PID,并且可以使用
杀()这一点。

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

谷歌搜索popen2()实现为一些示例code上
如何实现什么popen()完成在做什么。这只是十几线
长。从 dzone.com采取我们可以看到
像这样的例子:

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

#define READ 0
#define WRITE 1

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

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

注:好像popen2()是你想要的,但我的分布似乎并没有来用这种方法。

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