SIGTSTP(Ctrl-Z) 不適用於由腳本指令啟動的腳本

SIGTSTP(Ctrl-Z) 不適用於由腳本指令啟動的腳本

注意:script指的是script命令,它將 stdin 和 stdout 記錄到檔案中。

我試圖使用該 script實用程式運行一個腳本來保存輸出以供以後檢查,同時保留終端上的文字顏色。

  • Ctrl當我嘗試使用+ Z( )暫停當前腳本時SIGTSTP,控制台會列印^Z並且腳本不會停止。
  • 然後我嘗試了Ctrl+S ( SIGSTOP)。目前運行的腳本確實凍結(htop將所有進程顯示為Z模式),但它不會釋放終端。  Ctrl+Q確實恢復它們。

我現在很困惑為什麼SIGSTOP Ctrl+S有效,但SIGTSTP( Ctrl+ Z) 無效。

我知道可能會被困住,但我看不出有任何理由這樣做,而且的手冊頁SIGTSTP中也沒有任何相關內容。script我嘗試強制腳本解釋器進入互動模式,但結果讓我更加困惑。發出Ctrl+ Z( SIGTSTP) 確實會掛起正在執行的腳本,但script表示腳本已完成然後退出,這會殺死所有掛起的子進程。

在這種情況下有沒有辦法讓正常掛起?另外,有人能準確解釋一下發生了什麼事嗎?

答案1

就像任何其他直通工具(sshscreentmux等)一樣,script將呼叫終端置於原始模式,以便 Ctrl/Z 等字元不再產生中斷。然後它傳遞這些字符,內部終端設備“正常”處理它們,產生預期的信號。任何進程都可以選擇捕獲SIGTSTP但不能捕獲SIGSTOP

在這些範例中,我用來$指示命令列提示符:

$ script
Script started, output log file is 'typescript'.
$ sleep 5    # After starting this I hit Ctrl/Z

[1]+  Stopped                 sleep 5
$

如果您向script自己發送SIGTSTP信號,它似乎會感到困惑(也許是編程錯誤?),並且SIGCONT不會恢復它。但是,發送SIGINT或某些其他終止訊號會恢復script足夠長的時間以操作原始訊號SIGTSTP並暫停。然後嘗試恢復script命令並fg終止會話:

$ script
Script started, output log file is 'typescript'.
$ while date; do sleep 5; done
Mon, 15 Apr 2024 14:44:42
Mon, 15 Apr 2024 14:44:47

此時script接收SIGTSTP並停止執行其內部流程。隨後發送SIGCONT沒有明顯的差異。

發送SIGINT結果如下:

Mon, 15 Apr 2
[1]+  Stopped                 script

然後恢復命令:

$ fg
script

Session terminated, killing shell... ...killed.
Script done.

在我看來,你最好送到SIGSTOP進程裡面script。這是另一個例子:

$ script
Script started, output log file is 'typescript'.
$ while date; do sleep 5; done
Mon, 15 Apr 2024 14:48:31
Mon, 15 Apr 2024 14:48:36
Mon, 15 Apr 2024 14:48:41
Mon, 15 Apr 2024 14:48:46    # Here I sent SIGSTOP to the shell running the "while" loop
Mon, 15 Apr 2024 14:49:07
Mon, 15 Apr 2024 14:49:12    # Here I hit Ctrl/C to break the loop

$ exit
Script done.

相關內容