[英]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.