Reputation: 111
I am given a program that runs until it is stopped using ctrl + c. I need to find the pid of this process and then output information like user time, system time, and total time using a bash script. It is my understanding that in order to do this I need to run the process and then stop it inside the script and after I stop the program I am able to find the information. I am having issues with stopping the process inside the script.
#!/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.
Upvotes: 2
Views: 397
Reputation: 2955
Based on your description, this should do what you want (explanation added as comments inside code):
#!/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
I assumed here that cpu
is the program you mentioned.
Upvotes: 1