Markdown

Start a Linux Process / Command in Background

Start a Linux Process / Command in Background


#一般執行
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ sleep 300

#背景執行
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ sleep 300 &
[1] 2524

#背景執行
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ sleep 400 &
[2] 2528

#查看背景工作
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ jobs
[1]-  Running                 sleep 300 &
[2]+  Running                 sleep 400 &

cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ jobs -l
[1]-  2524 Running                 sleep 300 &
[2]+  2528 Running                 sleep 400 &

#帶回 foreground
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ fg %1
sleep 300

# ctrl + z 暫停並放到 background
[1]+  Stopped                 sleep 300

cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ # ctrl + z

# 此時背景中 pid 2524 狀態是 Stopped
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ jobs -l
[1]+  2524 Stopped                 sleep 300
[2]-  2528 Running                 sleep 400 &

# 使用 bg 讓 process 重新再背景執行
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ bg %1
[1]+ sleep 300 &

# 此時背景中 pid 2524 狀態是 Running
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ jobs -l
[1]-  2524 Running                 sleep 300 &
[2]+  2528 Running                 sleep 400 &

# 用 job sequence 砍掉 process
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ kill %2
[2]+  Terminated              sleep 400

# 用 pid 砍掉 process
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ kill 2524
[1]+  Terminated              sleep 300

# 沒東西了
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ jobs -l

# nohup 是一個 POSIX 命令,用於忽略 SIGHUP ("signal hang up" 譯:掛斷信號) 。 
# SIGHUP信號是終端註銷時所發送至程序的一個信號。
# 
# 有時候要執行花費時間較長的命令時,可以使用 nohup,
# 如此一來登出,或不小心斷線時,process 仍會在背景繼續執行
cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ nohup sleep 500 &
[1] 2562

cepar@DESKTOP-H3LUMQB MINGW64 ~/Desktop
$ nohup: ignoring input and appending output to 'nohup.out'
^C

留言