gpt4 book ai didi

bash - 获取定时进程的 PID,以及时间的输出

转载 作者:行者123 更新时间:2023-11-29 09:46:05 25 4
gpt4 key购买 nike

我有这行代码:

{ time cp $PWD/my_file $PWD/new_file ; } 2> my_log.log

我需要知道执行“cp”命令需要多长时间,我还需要获取“cp”的 PID。我只想打印“cp”进程的 PID 并在 my_log.log 文件中获取以下内容:

<output of time> 

我试过 PID=$! 但这不提供 cp 进程的 PID。

最佳答案

  • 首先,您需要将您的(定时)cp 命令发送到后台,并带有尾随 &,这样您就可以在启动后检查正在运行的进程.(我怀疑你已经在这样做了,但它目前没有反射(reflect)在问题中)。

  • $!,包含最近启动的后台作业的 PID 的特殊变量,在本例中反射(reflect)了运行 子 shell time命令,所以我们知道它是cp命令的parent进程。要获取(在本例中是唯一的)子进程:

    • 如果您的平台有非标准的 pgrep 实用程序(许多 Linux 发行版和 BSD/macOS 平台附带),请使用:
      pgrep -P $!

    • 否则,请使用以下符合 POSIX 标准的方法:
      ps -o pid=,ppid= | awk -v ppid=$! '$2 == ppid { print $1 }'

为方便起见,使用 prgep 将它们放在一起:

# Send the timed `cp` command to the background with a trailing `&`
{ time cp "$PWD/my_file" "$PWD/new_file"; } 2> my_log.log &

# Get the `cp` comand's PID via its parent PID, $!
cpPid=$(pgrep -P $!)

关于bash - 获取定时进程的 PID,以及时间的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44248932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com