【问题标题】:Start and Stop a process to find PID in Bash Script启动和停止进程以在 Bash 脚本中查找 PID
【发布时间】:2021-10-18 21:06:11
【问题描述】:

我得到了一个程序,该程序一直运行到使用 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.

【问题讨论】:

  • 您可以在后台运行它。然后PID将在$!

标签: bash pid script


【解决方案1】:

根据您的描述,这应该可以满足您的要求(在代码中添加为 cmets 的说明):

#!/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 是您提到的程序

【讨论】:

  • @101001:如果这有助于您的事业,请考虑将答案标记为已接受。
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多