为了确保 ollama 在后台运行时没有标准输入问题,你可以调整启动命令的结构。具体来说,我们可以避免命令尝试读取 stdin,并确保后台进程不依赖于终端输入。
下面是几种改进的方法:
方法 1:使用 nohup 并重定向所有输出
你已经使用了 nohup 来让进程在后台运行,但可以做一些调整以避免错误。
nohup ollama run llama3.3:70b > output.log 2>&1 < /dev/null &
这里有几个关键点:
> output.log 2>&1:将标准输出和标准错误输出都重定向到output.log文件。< /dev/null:确保没有输入来源,避免进程试图读取stdin。&:将进程放到后台。
方法 2:使用 screen 或 tmux(推荐用于长期运行的进程)
screen 或 tmux 是更适合长期运行进程的工具,可以在会话中保持进程运行,并且可以随时重新连接查看输出。
-
使用
screen:- 启动一个新的
screen会话:screen -S ollama_session - 在
screen会话中启动你的命令:ollama run llama3.3:70b > output.log 2>&1 < /dev/null - 按下
Ctrl + A然后按D,这将会把你从screen会话中分离出来,进程仍然在后台运行。 - 你可以随时通过以下命令重新连接到
screen会话:screen -r ollama_session
- 启动一个新的
-
使用
tmux:- 启动一个新的
tmux会话:tmux new-session -s ollama_session - 在
tmux会话中启动命令:ollama run llama3.3:70b > output.log 2>&1 < /dev/null - 按下
Ctrl + B然后按D,这将会把你从tmux会话中分离出来,进程仍然在后台运行。 - 你可以随时通过以下命令重新连接到
tmux会话:tmux attach-session -t ollama_session
- 启动一个新的
方法 3:使用 systemd 服务(适用于需要在系统启动时自动运行的情况)
如果你希望在系统启动时自动启动 ollama,并且希望它始终在后台运行,你可以创建一个 systemd 服务。
-
创建一个新的
systemd服务文件:sudo nano /etc/systemd/system/ollama.service -
在文件中输入以下内容:
[Unit] Description=Ollama Background Service After=network.target [Service] ExecStart=/usr/bin/ollama run llama3.3:70b > /path/to/output.log 2>&1 WorkingDirectory=/path/to/working/directory StandardInput=null StandardOutput=append:/path/to/output.log StandardError=append:/path/to/error.log Restart=always User=your_user Group=your_group [Install] WantedBy=multi-user.targetExecStart: 运行的命令,可以替换为实际的路径。StandardInput=null: 避免从stdin获取输入。StandardOutput和StandardError: 设置日志文件路径。Restart=always: 保证如果进程崩溃后会自动重启。
-
重新加载
systemd配置:sudo systemctl daemon-reload -
启动并启用服务:
sudo systemctl start ollama.service sudo systemctl enable ollama.service -
查看服务状态:
sudo systemctl status ollama.service
总结:
nohup方法适用于简单的后台进程运行,但要避免标准输入问题,可以使用< /dev/null来避免它。screen或tmux适用于需要会话管理的情况,能够分离和恢复会话。systemd适用于系统级的进程管理,特别适合需要长时间运行且在系统启动时自动启动的进程。
498

被折叠的 条评论
为什么被折叠?



