杀死一个进程开始的popen [英] kill a process started with popen

查看:662
本文介绍了杀死一个进程开始的popen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的popen 打开一个管道的过程后,有没有办法杀已经启动的进程? (使用函数,pclose 是不是我想要的,因为这将等待进程结束,但我要杀死它。)

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 that will wait for the process to finish, but I need to kill it.)

推荐答案

不要使用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.

这篇关于杀死一个进程开始的popen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆