给定一个程序,该程序一直运行,直到使用ctrl + c停止为止。我需要找到该进程的pid,然后使用bash脚本输出用户时间、系统时间和总时间等信息。我的理解是,为了做到这一点,我需要运行该进程,然后在脚本中停止它,在我停止程序后,我能够找到信息。我在脚本内停止进程时遇到问题。
#!/bin/bash
clarg="$1"
if [ "$clarg" == "cpu" ] ; then
gcc -o cpu cpu.c
./cpu
#This is where I'm lost and tried this out from online but
#didn't work for me
trap "exit" INT
while :
do
sl -e
done
#Commands to find PID info below.
根据你的描述,这应该做你想做的(解释作为代码内的注释添加):
#!/bin/bash
clarg="$1"
if [ "$clarg" == "cpu" ] ; then
gcc -o cpu cpu.c
# Run cpu via time in background, get pid of time process
time ./cpu &
ppid=$!
# Let cpu run for a while
sleep 15s
# Alternatively, wait for user to hit ENTER
#read -s -p "Hit ENTER to terminate cpu."
# Get pid of time's child process (i.e. pid of cpu process) and stop
# it by sending SIGINT (CTRL+C); time will exit and print its results
cpid=$(pgrep -P $ppid)
kill -INT $cpid
fi
我假定cpu
是您提到的程序。