php 檔案鎖定寫入

來源:互聯網
上載者:User
PHP檔案寫入方法,應對多線程寫入:

Php代碼

function file_write($file_name, $text, $mode='a', $timeout=30){      $handle = fopen($file_name, $mode);      while($timeout>0){          if ( flock($handle, LOCK_EX) ) {              $timeout--;              sleep(1);          }      }      if ( $timeout > 0 ){          fwrite($handle, $text.'\n');          flock($handle, LOCK_UN);          fclose($handle);          return true;      }      return false;  }

其中flock(int $handle, int $operation)函數操作的 handle 必須是一個已經開啟的檔案指標。

operation 可以是以下值之一:

要取得共用鎖定定(讀取的程式),將 operation 設為 LOCK_SH(PHP 4.0.1 以前的版本設定為 1)。

要取得獨佔鎖定(寫入的程式),將 operation 設為 LOCK_EX(PHP 4.0.1 以前的版本中設定為 2)。

要釋放鎖定(無論共用或獨佔),將 operation 設為 LOCK_UN(PHP 4.0.1 以前的版本中設定為 3)。

如果不希望 flock() 在鎖定時堵塞,則給 operation 加上 LOCK_NB(PHP 4.0.1 以前的版本中設定為 4)。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.