MacOS tends to *aggressively* turn off Wi-Fi and throttle or suspend background processes when a machine is idle.
This can break SSH sessions, running scripts...
You can disable system sleep entirely either via the CLI
```sh
sudo pmset -a sleep 0
```
However, this isn't exactly good for your battery or energy savings.
A better solution is to prevent sleep for temporarily using the `caffeinate` built-in command for specific processes using
```sh
caffeinate -dimsu -- tmux
```
or
```sh
caffeinate -dimsu -- yarn dev
```
or
```sh
caffeinate -dimsu
```
to create a persistent system-wide wake lock that lasts until you manually stop it.
Don't caffeinate the entire shell or system if you don't have to.
Coffee mode applies only to the process you've attached it to.
When it stops, so does coffee mode.
Flags breakdown:
`-d`: prevents display sleep
`-i`: prevents idle sleep
`-m`: prevents system from going to sleep when plugged into AC
`-s`: prevents system sleep when on battery
`-u`: declares user activity, telling macOS “I’m in use”
Everything after `--` is the command to run under the caffeinated environment.
This ensures your processes will keep running in the background, even when your computer is locked and regardless of its battery level.
___
You can `caffeinate` an already running process using the **`-w` (wait for process) flag**.
If your process has PID, run:
```sh
caffeinate -dimsu -w <pid>
```
To get the PID of a tmux session
```sh
pgrep tmux
```
For the PID of a running script
```sh
ps aux | grep your_script.sh
```
A one-liner to caffeinate tmux after the fact
```sh
caffeinate -dimsu -w $(pgrep tmux)
```
This continues until you stop caffeinate, i.e., until you press: `Ctrl + C`.