August 19, 2006

retty : 攔截終端機輸出的工具

[retty] 是個攔截終端機輸出的小工具,引用網頁介紹:
    retty is a tiny tool that lets you attach processes running on other terminals. So you were running that mutt outside of screen at your home machine and now wanna check your mail? Attach it with retty, do whatever you want, detach it again and everything is as it was before. You don't have to run them all in screen just in case.
看起來頗有意思,咱們來作個小實驗,當然還是用個 "Hello World" 等級的程式來作為切入: (hello.c)
    #include <stdio.h>
     
    int main(void)
    {
    	for ( ; ; )
    		printf("Hello World!\n");
    	return 0;
    }
編譯並執行:
    # gcc -o hello hello.c
    # ./hello
    
可想而知,畫面將輸出一堆 "Hello World!" 字樣,如下圖: (click to enlarge)

注意到右下方的視窗,接著,我們在左上方的視窗準備執行 [retty]。先來取得剛剛那個無限迴圈版 "Hello World" 的 Process ID:
    # pidof hello
    23726
    
因此,PID = 23726,然後依據 man ./retty.1 可得知使用方式,就來試試:
    # ./retty 23726
    
結果如何呢?咱們看看: (click to enlarge)

注意到左上角視窗,原本應該在右下角視窗的 "Hello World!" 的終端機輸出被「抓到」(attach) 到左上角去了,右下角最後一行只印出 "Hello W"。最後,我們回到右下角視窗,按下 Ctrl-C,結果左上角原本持續輸出的 "Hello World!" 也終止了,證實 [retty] 的效果,如果我們要追蹤某個背景執行的 process,就可派上用場,此外,該套件還提供另一個小工具 blindtty,搭配使用可增加 attach / detach 的彈性。

[retty] 目前只支援 Linux/x86,運作原理類似 Debugger,會安插一小段 bytecode 到特定的 process stack 中。稍早在 [2006 年七月份預定的演講] 的「深入淺出 Hello World」場次中有提及部份相關概念,日後或許會在 Part II 延續介紹。
由 jserv 發表於 August 19, 2006 11:45 AM
迴響