phantomjs没有关闭和离开孤儿进程

时间:2013-10-02 14:25:03

标签: memory-leaks webdriver phantomjs ghostdriver

在PhantomJS 1.9.2上,ubuntu 12 LTS和Ghostdirver 1.04以及selenium 2.35在我的测试之后我得到了悬空的phantomjs进程。任何人都知道如何解决这个问题的好方法吗?

这是一个演示奇怪行为的测试程序:

package testing;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

public class PhantomIsNotKilledDemo {

    private static WebDriver getDriver(){
        String browserPathStr = System.getProperty("selenium.pathToBrowser");
        if (browserPathStr == null) browserPathStr = "/home/user1/apps/phantomjs/bin/phantomjs";

        DesiredCapabilities caps = DesiredCapabilities.phantomjs();

        caps.setCapability("takesScreenshot", true);
        caps.setCapability(
                PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                browserPathStr );

        WebDriver driver = new PhantomJSDriver(caps);

        return driver;
    }

    public static void main(String[] args) {
        int max = 10;
        for (int i = 0; i < max; i++){
            WebDriver d1 = getDriver();
            d1.get("http://www.imdb.com/title/tt1951264");

            System.out.println("done with cycle " + (i+1) +" of "+max);
            d1.close();
            //d1.quit();
        }

        System.out.println("done");
        System.exit(0);
    }
}

要运行此操作,您应该将phantomjs二进制文件的路径作为系统属性提供,或者相应地设置变量。

让这次运行后我执行这个shell命令

ps -ef | grep phantomjs

找到10个悬空的幻影过程。

如果我使用d1.quit(),我最终没有悬空过程。这显然更好,但我仍然期望与.close获得相同的结果。

请注意,这是的交叉点 https://github.com/detro/ghostdriver/issues/162#issuecomment-25536311

更新此帖子根据Richard的建议进行了更改(见下文)。

2 个答案:

答案 0 :(得分:9)

您应该使用quit()来终止流程,而不是close()

正如您所发现的,close将关闭当前窗口(和浏览器),但不会关闭该进程。如果您要向流程发送其他命令或想要检查流程,这非常有用。

退出是为了关闭每个窗口并停止进程,这听起来就像你正在寻找的那样。

这两种方法的documentation为:

  

关闭()

     

关闭当前窗口,如果是,则退出浏览器   最后一个窗口当前打开。

     

<强>退出()

     

退出此驱动程序,关闭每个关联的窗口。

答案 1 :(得分:3)

我会将您的代码重写为以下内容:

public static void main(String[] args) {
    int max = 10;
    for (int i = 0; i < max; i++){
        WebDriver d1 = getDriver();

        d1.get("http://www.imdb.com/title/tt1951264");

        System.out.println("done with cycle " + (i+1) +" of "+max);
        d1.quit();
    }

    System.out.println("done");
    System.exit(0);
}

我不完全确定为什么.close()没有结束WebDriver。理论上,如果在最后打开的窗口中调用WebDriver,.close()应该退出。当调用该网址时,也许某事正在打开第二个窗口?或者.close()可能对phantomjs有不同的作用。

至于为什么.quit()没有关闭所有的phantomjs会话,你调用的最后一个getDriver()在循环之外没有相应的.quit()。我重构你的for循环来创建WebDriver的实例,执行你的测试,然后在每个循环结束时.quit()那个WebDriver / phantomjs会话。