MAC ulimit 的永久配置方案

23 min read

ulimit is a Unix shell command used to set resource limits for processes on your system. The default values for these limits might not be enough for some applications, like database servers, high-performance web servers, or development tools that handle many open files simultaneously.

To set the ulimit for file descriptors (number of open files) in Go, you'll need to change the limits on your macOS system, as this is not something you can change directly within your Go application.

Here's how to change the ulimit on macOS:

  1. Check the current ulimit values:

Open the terminal and run the following command:

ulimit -a

This will display the current limits for your system.

  1. Edit the limits configuration:

For macOS, you need to create a file called limit.maxfiles.plist in the /Library/LaunchDaemons directory.

First, create the file using a text editor like nano:

sudo nano /Library/LaunchDaemons/limit.maxfiles.plist

Then, copy and paste the following content into the file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>limit.maxfiles</string>
    <key>ProgramArguments</key>
    <array>
      <string>launchctl</string>
      <string>limit</string>
      <string>maxfiles</string>
      <string>65536</string>
      <string>65536</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>ServiceIPC</key>
    <false/>
  </dict>
</plist>

In this example, the limit is set to 65536. You can change this number to your desired limit, but be cautious not to set it too high, as it may cause system instability.

Save the file and exit the text editor.

  1. Change the file permissions and owner:

Run the following commands to ensure the file has the correct permissions and owner:

sudo chown root:wheel /Library/LaunchDaemons/limit.maxfiles.plist
sudo chmod 644 /Library/LaunchDaemons/limit.maxfiles.plist
  1. Load the new configuration:

To load the new configuration, run the following command:

sudo launchctl load -w /Library/LaunchDaemons/limit.maxfiles.plist
  1. Restart your Mac:

After restarting your Mac, the new ulimit settings should take effect. You can verify the changes by running ulimit -a again in the terminal.

These steps will change the ulimit settings on your macOS system, which will also affect Go applications running on the system.