我想檢查我的程序需要多長時間。然後我使用「/ usr/bin/time my_program」。當它需要超過5秒鐘,我想殺死它。我試過「kill -9 TIME_S_PID」,時間被殺死,但my_program仍在運行。那麼如何殺死my_program?當我運行/ usr/bin/time my_program時,如何殺死my_program?
謝謝。
我想檢查我的程序需要多長時間。然後我使用「/ usr/bin/time my_program」。當它需要超過5秒鐘,我想殺死它。我試過「kill -9 TIME_S_PID」,時間被殺死,但my_program仍在運行。那麼如何殺死my_program?當我運行/ usr/bin/time my_program時,如何殺死my_program?
謝謝。
請注意,killall
,顧名思義,將殺死您的程序的所有實例。更好的辦法是使包裝腳本:
#!/bin/sh
echo "$$" # print the PID of the current process
exec my_program
然後你執行/usr/bin/time my_wrapper_script
,打印程序的該實例的PID,當你想與kill -9 "$my_prog_pid"
殺死它。
正如@Soulseekah所說,killall my_program的作品。
我解決了這個用下面2個腳本:
第一我命名爲指明MyTime對應
#!/bin/bash
##############################################################################################################
# This script is used to perform a /usr/bin/time over a command and deliver the kill signal to the good exe
# Usage : mytime command args
# The result will be in a file name /tmp/command.PID.txt where pid is the current pid
# example:
# ./mytime sleep 10000 &
# kill pid of mytime
# cat /tmp/sleep.*.txt
##############################################################################################################
# store the current pid
P=$$
CMD=$1
signalisation()
{
# deliver the signal to good pid ie the son of /usr/bin/time
S=$1
# echo Signal $S >>/tmp/trace_$P.txt
PF=$(cat /tmp/pid$P.txt)
rm /tmp/pid$P.txt
# echo pid du fils de time : $PF >>/tmp/trace_$P.txt
kill $S $PF
}
trap "signalisation 1" 1
trap "signalisation 2" 2
trap "signalisation 3" 3
trap "signalisation 15" 15
/usr/bin/time -f '%e %M # Elapsed real time (in seconds) and Memory Max' -o /tmp/$CMD.$P.txt storepid /tmp/pid$P.txt $* &
wait %1
exit $?
而這一次由以前我命名用它storepid
#!/bin/bash
###########################################################################################
# this script store the pid in the file specified by the first argument
# the it executes the command defined by the others arguments
# example:
# storepid /tmp/mypid.txt sleep 100
# result sleep 100 secondes , but you can kill it before using kill $(cat /tmp/mypid.txt)
###########################################################################################
WHERE=$1
shift
echo $$ >$WHERE
exec $*
應該是superuser.com的問題,帶有「unix」和「kill」標籤。 – 2010-10-28 07:43:22
試試'killall my_program' – soulseekah 2010-10-28 07:45:19
謝謝!好主意。 – 2010-10-28 08:25:38