【问题标题】:Failed to open stream: Too many open files无法打开流:打开的文件太多
【发布时间】:2013-04-02 23:35:34
【问题描述】:

我正在为在共享主机中运行的客户端编写 PHP CLI 脚本。它使用一个简单的函数记录到一个文件,例如:

function log_entry($msg) {
    global $log_file, $log_handle;
    $msg =  "[".date('Y-m-d H:i:s')."] ".$msg."\n";
    echo $msg;
    $log_handle = fopen($log_file, 'a');
    fwrite($log_handle, $msg);
}

我得到这个错误:

PHP Warning:  fopen(./logs/sync.20130410.log) 
[<a href='function.fopen'>function.fopen</a>]: failed to open stream: 
Too many open files in ./functions.php on line 61

我认为使用相同的句柄有问题,所以我将其更改为:

function log_entry($msg) {
    global $log_file;
    $msg =  "[".date('Y-m-d H:i:s')."] ".$msg."\n";
    echo $msg;
    $log_handle = fopen($log_file, 'a');
    fwrite($log_handle, $msg);
    fclose($log_handle);
}

但这没有用。我总是在同一日志行中收到错误。当我执行ulimit -n 时,我得到 1024,但这不应该成为问题,因为我从不打开多个文件。想法?

【问题讨论】:

  • 您的共享主机提供商可能会遇到文件描述符限制
  • 但是我不是一次只使用一个同时具有两个功能吗?第一个应该在整个执行过程中只使用一个,而第二个应该每行使用一个......还是有不同的工作方式?
  • ss64.com/bash/ulimit.html ... apache 可以配置为将其 ulimit 降低到它打开的文件数,从而限制您打开其他文件。您应该与您的托管服务提供商核实配置
  • @Zak 这是一个PHP脚本,不过是通过CLI执行的,所以Apache不在中间

标签: linux logging php


【解决方案1】:

发现问题。我正在回答这个问题,以防万一有人出于同样的原因使用 Google 搜索,但我知道问题中并没有暗示这个答案。

我正在使用 BigCommerce API 客户端,结果发现他们正在为每个请求打开一个句柄并使我的脚本崩溃。这是我修复它的方法:

BigCommerce/API/Connection.php:354-365:

public function put($url, $body)
{
    $this->addHeader('Content-Type', $this->getContentType());

    if (!is_string($body)) {
        $body = json_encode($body);
    }

    $this->initializeRequest();
    $handle = tmpfile();
    fwrite($handle, $body);
    fseek($handle, 0);
    curl_setopt($this->curl, CURLOPT_INFILE, $handle);
    curl_setopt($this->curl, CURLOPT_INFILESIZE, strlen($body));

    curl_setopt($this->curl, CURLOPT_URL, $url);
    curl_setopt($this->curl, CURLOPT_PUT, true);
    curl_exec($this->curl);
    fclose($handle); // Added this line

    return $this->handleResponse();
}

(添加了fclose($handle);)行。

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 2012-08-14
    • 2013-11-15
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多