Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

วิธีรัน Process ใน Background ด้วย nohup ใน Linux

คู่มือนี้สอนใช้ nohup รันคำสั่ง/สคริปต์ใน Background ค้างไว้แม้ Logout/Disconnect SSH

nohup คืออะไร?

  • No Hang Up - ไม่สนใจ SIGHUP Signal (ส่งเมื่อ Terminal ปิด/Logout)
  • ทำให้ Process ทำงานต่อไปได้แม้ User ออกจากระบบ
  • Output ถูก Redirect ไป nohup.out อัตโนมัติ

Syntax พื้นฐาน

nohup command [args] &
  • & - รันใน Background (Job Control)
  • หรือใช้ nohup command > output.log 2>&1 & ระบุไฟล์ Log เอง

ตัวอย่าง: Backup MySQL ใหญ่

# 1. SSH เข้าเซิร์ฟเวอร์
ssh user@server

# 2. รัน mysqldump ด้วย nohup
nohup mysqldump -u user -p'password' large_db > large_db.sql &

# Output:
# [1] 12345
# nohup: appending output to 'nohup.out'

ตรวจสอบ Process

# ดู PID จาก output (12345)
ps -ef | grep 12345

# หรือดู Jobs ของ Shell
jobs
# [1]+  Running  nohup mysqldump ...

# ดู Output จริง
tail -f nohup.out

เมื่อ Process เสร็จ


[1]+  Done    nohup mysqldump -u user -p'password' large_db > large_db.sql

ตรวจสอบ nohup.out สำหรับ Error/Warning

เทคนิคขั้นสูง

เปรียบเทียบ

เทคนิคคำสั่งคำอธิบาย
Disowncommand & disown -h %1แยก Job จาก Shell (ไม่ได้รับ SIGHUP)
Screenscreen -S backupTerminal Multiplexer - Detach/Attach ได้
Tmuxtmux new -s backupScreen ตัวใหม่ ทรงพลังกว่า
Systemd Servicesystemd-run --user commandจัดการเป็น Service พร้อม Logging/Restart
At/Batchat now + 1 hour < script.shSchedule รันภายหลัง

Best Practice

  • ใช้ nohup cmd > log.txt 2>&1 & ระบุ Log file ชัดเจน
  • บันทึก PID: echo $! > /var/run/myscript.pid
  • ตรวจสอบ Disk Space ก่อนรัน Job ใหญ่
  • ใช้ timeout จำกัดเวลารันสูงสุด

nohup เป็นเครื่องมือพื้นฐานที่ทุก Linux User ควรรู้ สำหรับงานที่รอไม่ได้นาน

Toolเหมาะสำหรับความยาก
nohup &Command เดียว ใช้ครั้งคราวง่าย
Screen/TmuxInteractive, หลายหน้าต่าง, Resume ได้ปานกลาง
SystemdProduction Service, Auto-restart, Loggingสูง