温馨提示×

怎样后台运行进程

小樊
55
2026-09-27 17:38:18
栏目: 编程语言

“后台运行进程”在不同操作系统、不同使用场景下方法不一样。下面按常见场景给你总结:


一、Linux / macOS 终端

1. 用 & 后台运行

command &

例如:

python server.py &
  • 关闭终端可能中断进程(取决于 shell 设置)

2. 用 nohup(推荐)

nohup command > output.log 2>&1 &
  • 关闭终端也不会退出
  • 输出写入 output.log

3. 用 setsid

setsid command
  • 完全脱离终端会话

4. 用 screen / tmux(最常用)

tmux
# 在 tmux 里运行命令
# Ctrl+B D 脱离

重新进入:

tmux attach

5. 用 systemd(正式服务)

# /etc/systemd/system/myapp.service
[Unit]
Description=My App

[Service]
ExecStart=/usr/bin/python /path/server.py
Restart=always

[Install]
WantedBy=multi-user.target
systemctl start myapp
systemctl enable myapp

二、Windows

1. 命令行后台

start /B command

2. PowerShell

Start-Process -NoNewWindow command

3. 作为服务运行

  • 使用 nssm 或 sc create

三、程序语言内后台

Python

import subprocess
subprocess.Popen(["python", "server.py"])

Java

new ProcessBuilder("cmd").start();

四、查看 / 管理后台进程

  • Linux:jobs、ps、kill
  • Windows:tasklist、taskkill

如果你能说明:

  • 用什么系统(Linux / Windows / macOS)
  • 是临时跑还是长期服务
  • 用什么语言/命令

我可以给你更精确的做法。

0 踩