最近有个疑问,netstat  -antup|head  -500   类似这条命令中,是netstat 执行完然后截取前500条记录还是,netstat 与head 并行执行,netstat 执行完500条就不再继续?



最终答案由酷学园darkdanger大大提供:



唔,我先前都沒有想過這個問題呢....
查了一下再加上一些驗證後
我想管線命令的執行狀況大概是這樣:
1.
管線命令會觸發一個緩衝區(buffer)的建立,讓不同程式從中讀取、寫入資料
2.
管線最末端的程式結束時會觸發緩衝區停止擴充
3.
管線前端的程式則會因為無法再寫入至緩衝區、發生錯誤而終止

測試程式:

代碼: [選擇]

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
p = 0

txt = open("log.txt", "w")

while p < int(sys.argv[1]):
    p = p + 1
    txt.write("%d\n" % p)
    print(p)

txt.close()

程式列印 1000 次,儘管 head 後只顯示 5,但 log.txt 仍寫入了 1000 行:

代碼: [選擇]

./pipe_test.py 1000 |head -5
程式列印 3000 次,出現 IOError,log.txt 內則寫入了 2680 行:

代碼: [選擇]

./pipe_test.py 3000 |head -5

代碼: [選擇]

IOError: [Errno 32] Broken pipe
若改寫成忽略 IOError:

代碼: [選擇]

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
p = 0

txt = open("log.txt", "w")

while p < int(sys.argv[1]):
    p = p + 1
    txt.write("%d\n" % p)

    try:
        print(p)
    except IOError as error:
        pass

txt.close()

則 log.txt 可以順利寫入到 3000 行