Answers:
看似复杂的要求:-)
分两部分,第一部分 pstrace
包装脚本 strace
,这用 pgrep
用于名称到PID的操作。
#!/bin/bash
IFS=$' \t\n'
# process the arguments to find "-p procname", only support one instance though
for ((nn=1; nn<=$#; nn++)); do
if [ "${!nn}" = "-p" ]; then
:
elif [ "$prev" = "-p" ]; then
pname="${!nn}"
else
args+=( "${!nn}" ) # just copy
fi
prev="${!nn}"
done
pids=()
if [ -n "$pname" ]; then
# skip this shell's PID, which pgrep -f will match
# note the use of exec to avoid picking up a matching subshell too
# uncomment && printf for pid/pname list
while read pp pname; do
[ "$pp" != "$$" ] && pids+=($pp) # && printf "%6i %s\n" "$pp" "$pname"
done < <(exec pgrep -l -f "${pname}")
fi
npids=${#pids[*]}
if [ $npids -eq 0 ]; then
echo "No PIDs to trace."; exit 2
elif [ $npids -eq 1 ]; then
args=( "${args[@]}" -p ${pids[0]} )
elif [ $npids -le 32 ]; then
read -p "$npids PIDS found, enter Y to proceed: " yy
[ "$yy" != "Y" ] && echo "Cancelled..." && exit 1
args=( "${args[@]}" ${pids[@]/#/-p } )
else
echo "Too many PIDs to trace: $npids (max 32)."; exit 2
fi
strace "${args[@]}"
对于我将使用的第二部分 bash
可编程完成以按名称完成流程,将其放入您的 ~/.bash_profile
或类似的:
# process-name patterns to ignore
PROCIGNORE=( "^\[", "^-bash" )
_c8n_listprocs ()
{
local cur prv ignore IFS nn mm
prv=${COMP_WORDS[COMP_CWORD-1]}
cur=${COMP_WORDS[COMP_CWORD]}
case "$prv" in
'-p')
IFS=$'\n' COMPREPLY=( $(ps axwwo "args") ) IFS=$' \t\n'
COMPREPLY=(${COMPREPLY[*]// */}) # remove arguments
ignore="0" # ps header
for ((nn=1; nn<${#COMPREPLY[*]}; nn++)); do
# filter by (partially) typed name in cur
# use " =~ ^$cur " for prefix match, without ^ it's substr match
[[ -n "$cur" && ! "${COMPREPLY[$nn]}" =~ $cur ]] && {
ignore="$nn $ignore"
} || {
# skip names matching PROCIGNORE[]
for ((mm=0; mm<${#PROCIGNORE[*]}; mm++)); do
[[ "${COMPREPLY[$nn]}" =~ ${PROCIGNORE[$mm]} ]] &&
ignore="$nn $ignore"
done
}
done
# remove unwanted, in reverse index order
for nn in $ignore; do unset COMPREPLY[$nn]; done
;;
*) COMPREPLY=()
;;
esac
}
complete -F _c8n_listprocs pstrace
经过测试和测试在linux上使用bash-3.x和bash-4.x。 ps
选项可能需要在非Linux平台上进行调整,也应该支持 truss
一线改变。
限制包括:
[names]
这会导致 pgrep
(可能)不做你想要的 args
“用来代替” comm
“ 以便 /paths
可以使用,如果有的话)