为什么我得到不同的结果用kill -0(小于JOBSPEC> | PID) [英] why do I get different results with kill -0 (<jobspec>|pid)

查看:160
本文介绍了为什么我得到不同的结果用kill -0(小于JOBSPEC> | PID)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个脚本,将启动另一个进程,并在一段时间后杀死它,如果它没有自行退出。自从开始这个,我才明白了暂停命令这样做正确的方式,但我仍然感到困惑,为什么我的方法之一是失败的。

I am writing a script that will launch another process and after a period of time kill it if it hasn't exited on its own. Since starting this, I came to realize that the timeout command is the right way to do this, but I'm still confused about why one of my approaches was failing.

下面是我试图:

#!/bin/bash

backgroundScript.sh &

for((i=0; i<60; i++)); do
    if ! kill -0 %1; then
        exit
    fi
    sleep 1
done

kill %1

我很惊讶地发现,杀-0%1 总是成功,即使在后台完成该过程后。如果我用PID的过程,所以如果内环路变成了:

I was surprised to find that kill -0 %1 was always succeeding, even when the process in the background finished. If I used the PID for that process, so the if within the loop became:

    if ! kill -0 $!; then

它工作得很好。那么,为什么不JOBSPEC为我工作呢?

it worked fine. So why wasn't the jobspec working for me there?

推荐答案

好吧,一群挖我已经发现后为什么杀-0%1 显示作业仍而存在杀-0 $!显示进程已退出。直到呼叫方已经通知的bash不会获得这份工作。在交互的shell将打印到屏幕上的作业终止。在非交互的shell,这意味着调用脚本有机会获得进程的返回值。

Ok, after a bunch of digging I have uncovered why kill -0 %1 shows the job still exists while kill -0 $! shows the process has exited. bash will not reap the job until the caller has been notified. In an interactive shell that will print to the screen the job termination. In a non-interactive shell, this means the calling script has had a chance to get the return value of the process.

一个是通风报信我送行从庆典源的相关评论是jobs.c:

One of the relevant comments that tipped me off from the bash source is in jobs.c:

/ *标记为通知都死了工作,所以delete_job()清理出来
     工作表的正确。 POSIX.2说,我们需要保存
     最后CHILD_MAX工作状态,所以我们计算的死亡人数
     就业和标志只有足够的通知,以节省CHILD_MAX状态。 * /

/* Mark all dead jobs as notified, so delete_job () cleans them out of the job table properly. POSIX.2 says we need to save the status of the last CHILD_MAX jobs, so we count the number of dead jobs and mark only enough as notified to save CHILD_MAX statuses. */

而在 wait_for_single_pid 函数这个片段:

/* POSIX.2: if we just waited for a job, we can remove it from the jobs
 table. */
BLOCK_CHILD (set, oset);
job = find_job (pid, 0, NULL);
if (job != NO_JOB && jobs[job] && DEADJOB (job))
  jobs[job]->flags |= J_NOTIFIED;
UNBLOCK_CHILD (oset);

直到呼叫方已通知该工作已经完成,它没有这样做。与之相关的进程可能会完成,但工作本身尚未完成。

Until the caller has been notified that the job is done, it is not done. The process related to it might be done, but the job itself is not done.

这篇关于为什么我得到不同的结果用kill -0(小于JOBSPEC&GT; | PID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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