[英]Why doesn't “xargs sudo perf top” work as expected?
我想分析一個進程,所以首先獲取它的 pid,然后使用“ perf top
”來檢查它:
$ pgrep program
14472
$ sudo perf top -p 14472
它按預期工作:
然后我想使用 pipe 來連接這兩個命令,所以我使用xargs
:
$ pgrep program | sudo xargs perf top -p
但這一次“ perf top
”似乎無法正常工作: 我比較了這兩個操作的過程:
(1)分別運行pgrep
和perf
:
$ ps -ef | grep perf
root 18468 16827 0 09:34 pts/3 00:00:00 sudo perf top -p 14472
root 18469 18468 91 09:34 pts/3 00:00:06 perf top -p 14472
nanxiao 18477 18295 0 09:34 pts/4 00:00:00 grep --color=auto perf
(2) 使用xargs
連接pgrep
和perf
:
$ ps -ef | grep perf
nanxiao 18250 16827 0 09:32 pts/3 00:00:00 xargs sudo perf top -p
root 18251 18250 0 09:32 pts/3 00:00:00 sudo perf top -p 14472
root 18252 18251 87 09:32 pts/3 00:01:47 perf top -p 14472
nanxiao 18442 18295 0 09:34 pts/4 00:00:00 grep --color=auto perf
恕我直言,看起來一樣。 任何人都可以提供一些線索嗎? 提前致謝!
PS,我的操作系統是CentOS 7
。
再次檢查手冊后,我發現-o
選項可以解決此問題:
-o, --open-tty 在執行命令之前,在子進程中重新打開標准輸入為 /dev/tty。 如果您希望 xargs 運行交互式應用程序,這將很有用。
命令是這樣的:
$ pgrep program | sudo xargs -o perf top -p
但不幸的是, CentOS 7
的xargs
有點老了,沒有提供這個選項。
根本原因是:沒有-o
選項perf
stdin
的標准輸入是/dev/null
:
$ sudo lsof -p 1495
......
perf 1495 root 0r CHR 1,3 0t0 2052 /dev/null
......
並且性能在perf
()中被阻止:
......
FD_ZERO(&read_set);
FD_SET(0, &read_set);
if (delay_secs) {
timeout.tv_sec = delay_secs;
timeout.tv_usec = 0;
}
err = select(1, &read_set, NULL, NULL, ptimeout);
if (err == 0)
return K_TIMER;
if (err == -1) {
if (errno == EINTR)
return K_RESIZE;
return K_ERROR;
}
key = SLang_getkey();
if (key != K_ESC)
return key;
......
讀取/dev/null
將返回EOF
,然后select()
將返回1
。
使用-o
選項, perf
程序的標准輸入是/dev/tty
stdin
$ sudo lsof -p 1394
......
perf 1394 root 0u CHR 136,25 0t0 28 /dev/pts/25
......
在上面的代碼中, select()
將返回0
,整個 function 將相應地返回。
更好的方法是直接在pgrep
的 output 上運行top
,而不是通過xargs
管道。 我相信默認情況下top
命令不會通過標准輸入讀取信息
sudo perf top -p "$(pgrep program)"
這樣$(..)
返回pgrep
命令的 output 並且返回的值作為位置參數值傳遞給-p
標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.