LoginSignup
16
12

More than 5 years have passed since last update.

Pythonにおけるファイルディスクリプタ上限設定

Posted at

Pythonにおけるファイルディスクリプタ上限設定

問題

以下のような、Too many open filesのエラーは、現在開いているファイル数が、ファイルディスクリプタの上限に達してしまっていることが原因で発生している。

 pipe creation failed (24): Too many open files
E0314 13:15:11.940766000 123145865863168 ev_poll_posix.cc:981]         pollset_work: {"created":"@1552536911.940755000","description":"OS Error","errno":24,"file":"src/core/lib/iomgr/wakeup_fd_pipe.cc","file_line":41,"os_error":"Too many open files","syscall":"pipe"}
E0314 13:15:11.940766000 123146633117696 completion_queue.cc:1036]     Completion queue next failed: {"created":"@1552536911.939034000","description":"OS Error","errno":24,"file":"src/core/lib/iomgr/wakeup_fd_pipe.cc","file_line":41,"os_error":"Too many open files","syscall":"pipe"}

open('file_path')の周辺でエラーが起きているときは、きちんとcloseしましょうという対策となるが
マルチスレッドや、プロセス間通信をするときにもファイルディスクリプタを消費するので、そういうケースには上限値を設定するのも有効な手段である。

ファイルディスクリプタの上限値設定

ファイルディスクリプタの上限には複数種類がある
- Linux/mac側のファイルディスクリプタ上限(ソフトリミット、ハードリミット)
- Pythonのファイルディスクリプタ上限(ソフトリミット、ハードリミット)

Linux/mac側のファイルディスクリプタ上限(ソフトリミット、ハードリミット)の変更

以下のコマンドで、現在、1つのプロセスが使えるファイルディスクリプタの上限が確認できる

$ ulimit -n
1024

以下のコマンドで、現在、1つのプロセスが使えるファイルディスクリプタの上限が変更できる。
以下の例では8192に変更している

$ ulimit -n 8192

Pythonのファイルディスクリプタ上限(ソフトリミット、ハードリミット)

同様にPython内でも、1つのプロセスが使える上限のファイルディスクリプタが設定されている。
以下のコマンドで、現在Pythonから使用しているファイルディスクリプタ(FD)が確認できる

lsof -c python

以下のコマンドで、プログラム中から、現在のファイルディスクリプタのソフトリミット/ハードリミットが確認できる。

▼公式解説
https://docs.python.org/ja/3/library/resource.html

import resource
print(resource.getrlimit(resource.RLIMIT_NOFILE))

以下のコマンドで、ファイルディスクリプタのソフトリミット/ハードリミットを変更できる。

import resource
resource.setrlimit(resource.RLIMIT_NOFILE, (8192, 9223372036854775807))
16
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
12