[英]Start and Stop a process to find PID in Bash Script
我得到了一个程序,该程序在使用 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
是您提到的程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.