dougou8552 2009-05-20 04:15
浏览 133
已采纳

popen和文件操作

related to this question

my script basically runs fine but sometimes it stop responding at the fread function call and I can't seem to find the reason of the failure.

private function run_lengthy_job($command, $message) {
    for($handle = popen($command, 'r'); !feof($handle); sleep(2)) {
        printf("[%s]\t%s
", time(), $message);

        // log the operation
        exec(sprintf('logger "%s"', 
            escapeshellarg(fread($handle, 1024))));
    }

    pclose($handle);
}

example command

hg clone -v --debug http://some.repository.com/hgwebdir.cgi/some_repo some_repo

for now it is failing while cloning a large repository. the same problem persists even if I change fread to fgets.

Brief information about my php environment,

PHP 5.2.4-2ubuntu5.6 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 17 2009 14:29:38) 
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
    with Xdebug v2.0.3, Copyright (c) 2002-2007, by Derick Rethans

Running on ubuntu 8.04.2

EDIT: tried proc_open instead of popen and the script stuck at the same place. EDIT: replaced fread with stream_get_contents, but still stuck at the same place...

  • 写回答

1条回答 默认 最新

  • dsizmmwnm56437180 2009-05-20 07:05
    关注

    My current solution

    private function run_lengthy_job($command, $message) {
        printf("%s\t", $message);
    
        for($handle = popen($command, 'r'),
            stream_set_blocking($handle, FALSE),
            stream_set_timeout($handle, 3); 
            !feof($handle); sleep(1)) {
    
            echo '.';
    
            exec(sprintf('logger "%s"', 
                escapeshellarg(stream_get_contents($handle))));
        }
    
        $exit_status = pclose($handle);
    
        if(pcntl_wifexited($exit_status) 
            && pcntl_wexitstatus($exit_status) == 0) {
            echo "done!
    ";
        } else {
            echo "failed!
    ";
        }
    }
    

    the long waiting time occurred while calling fread is probably because access to the $handle is being blocked for popen to write output into it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示