[已解決] Linux 錯誤訊息: The configured user limit (128) on the number of inotify instances has been reached

筆者最近嘗試在 Linux 上開發 dotnet ,一執行 dotnet watch 指令就出現以下錯誤訊息:
    
dotnet watch
dotnet watch 🔥 Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload.
  💡 Press "Ctrl + R" to restart.
dotnet watch 🔧 Building...
  Determining projects to restore...
dotnet watch ❌ System.IO.IOException: The configured user limit (128) on the number of inotify instances has been reached, or the per-process limit on the number of open file descriptors has been reached.
   at System.IO.FileSystemWatcher.StartRaisingEvents()
   at Microsoft.DotNet.Watcher.Internal.DotnetFileWatcher.set_EnableRaisingEvents(Boolean value)
   at Microsoft.DotNet.Watcher.Internal.FileWatcher.AddDirectoryWatcher(String directory)
   at Microsoft.DotNet.Watcher.Internal.FileWatcher.WatchDirectory(String directory)
   at Microsoft.DotNet.Watcher.Internal.FileSetWatcher.GetChangedFileAsync(CancellationToken cancellationToken, Action startedWatching)
   at Microsoft.DotNet.Watcher.Tools.DotNetBuildFilter.ProcessAsync(DotNetWatchContext context, CancellationToken cancellationToken)
   at Microsoft.DotNet.Watcher.HotReloadDotNetWatcher.WatchAsync(DotNetWatchContext context, CancellationToken cancellationToken)
   at Microsoft.DotNet.Watcher.Program.RunAsync(CommandLineOptions options, CancellationToken cancellationToken)
   at Microsoft.DotNet.Watcher.Program.RunAsync(CommandLineOptions options, CancellationToken cancellationToken)
   at Microsoft.DotNet.Watcher.Program.RunAsync(String[] args)
dotnet watch ❌ An unexpected error occurred
    

原因是因為 Linux 有限制每個處理程序可以開啟的文件數量,dotnet watch 使用 inotify 監視檔案變化,超過了預設 128 的限制,我們可以修改 Linux 設定檔來解決這個問題。

查看當前 inotify 的數量限制:
    
cat /proc/sys/fs/inotify/max_user_instances
128
    

修改 sysctl.conf 設定檔:
    
sudo vi /etc/sysctl.conf
    

在檔案最後方加上以下指令,將限制提高為 512
    
fs.inotify.max_user_instances=512
    

重新讀取設定檔:
    
sudo sysctl -p
fs.inotify.max_user_instances = 512
    

再次查看 inotify 的數量限制:
    
cat /proc/sys/fs/inotify/max_user_instances
512
    

之後再次執行 dotnet watch 就可以正常執行了!

留言