Bash:是否可以阻止PID重新使用? [英] Bash: Is it possible to stop a PID from being reused?

查看:125
本文介绍了Bash:是否可以阻止PID重新使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以阻止PID再次使用?

Is it possible to stop a PID from being reused?

例如,如果我在后台使用myjob &运行作业myjob,并使用PID=$!获取PID,是否有可能防止linux系统重新使用该PID,直到我检查了PID不再存在(过程已完成)?

For example if I run a job myjob in the background with myjob &, and get the PID using PID=$!, is it possible to prevent the linux system from re-using that PID until I have checked that the PID no longer exists (the process has finished)?

换句话说,我想做类似的事情:

In other words I want to do something like:

myjob &
PID=$!
do_not_use_this_pid $PID
wait $PID
allow_use_of_this_pid $PID

在上面的示例中,这样做的原因并没有多大意义,但可以考虑依次启动多个后台作业,然后等待它们全部完成.

The reasons for wanting to do this do not make much sense in the example given above, but consider launching multiple background jobs in series and then waiting for them all to finish.

一些程序员伙计正确地指出,没有2个进程可以共享相同的PID.没错,但这不是我在这里问的.我正在要求一种防止使用特定PID启动进程后重新使用PID的方法.然后还有一种在我用完它以检查我的原始过程是否完成之后稍后重新启用它的方法.

Some programmer dude rightly points out that no 2 processes may share the same PID. That is correct, but not what I am asking here. I am asking for a method of preventing a PID from being re-used after a process has been launched with a particular PID. And then also a method of re-enabling its use later after I have finished using it to check whether my original process finished.

自从被问到以来,这是一个用例:

Since it has been asked for, here is a use case:

  • 启动多个后台作业
  • 获取后台作业的PID
  • 防止PID在后台作业终止后被其他进程重复使用
  • 检查后台作业"的PID-即确保后台作业完成
  • [请注意,如果为后台作业的PID禁用了PID重复使用,则那些PID不能被在后台进程终止后启动的新进程使用] *
  • 重新启用后台作业的PID
  • 重复

*进一步的解释:

  • 假设启动了10个职位
  • 5号工作退出
  • 另一个用户启动的新进程,例如,他们登录到tty
  • 新进程的ID与作业5相同!
  • 现在我们的脚本检查Job 5的终止,但是看到tty正在使用PID!

推荐答案

您不能阻止" PID被内核重用.但是,我倾向于认为这对您来说并不是真正的问题.

You can't "block" a PID from being reused by the kernel. However, I am inclined to think this isn't really a problem for you.

但是请考虑依次启动多个后台作业,然后等待它们全部完成.

but consider launching multiple background jobs in series and then waiting for them all to finish.

一个简单的wait(不带参数)将等待所有子进程完成.因此,您无需担心 PID正在重用.

A simple wait (without arguments) would wait for all the child processes to complete. So, you don't need to worry about the PIDs being reused.

启动多个后台进程时,PID实际上很可能会被其他进程重用. 但这不是问题,因为除非是子进程,否则您无法在该进程上wait.

When you launch several background process, it's indeed possible that PIDs may be reused by other processes. But it's not a problem because you can't wait on a process unless it's your child process.

否则,检查通过wait以外的任何其他方式启动的后台作业是否总是不可靠.

Otherwise, checking whether one of the background jobs you started is completed by any means other than wait is always going to unreliable.

这篇关于Bash:是否可以阻止PID重新使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆