开发者

Can I link a process to a file in bash?

I would like to do the following:

I want开发者_如何学Go to link a process A to a file F, so:

  • If F dissapears A crashes.
  • F will only dissapear when A finishes.

Is this possible? Thank you very much.


You should not avoid PIDs. They are process identifiers, and meant to be used.

Bash automatically monitors child processes it starts. The most recent background process id is maintained in $!. Bash also supports job controls using '%n' syntax.

You can trap child procs status changes with trap SIGCHLD, and you can "wait" for one or all child processes to complete with the wait command.

Here is a rough approximation of your two process monitoring, which consists of "job1" and "job2" being started the the sample script:

job1 &    # start job1 in background
j1pid=$!  # get its process id
job2 &    # start job2 in background
j2pid=$1  # get its process id

trap 'err=1' ERR  # trap all errors
err=
wait $j1pid  # wait for job1 to complete

# at this point job1 could have completed normally,
# or either process could have had an error

trap - ERR   # revert to "normal" handling of most errors

# kill the processes nicely, or abruptly
# kill -TERM sends the TERM signal to the process, which it can trap
# and do whatever pre-exit process is needed.
# kill -9 cannot be trapped.

for pid in $j1pid $j2pid ; do
  kill -TERM $pid 2>/dev/null || kill -9 $pid
done


You already have a file with almost this property on Linux. If you created a process, the /proc/procNum will exist while the process is alive. As an example, if your process number is 1050, the /proc/1050 will exist until the process die. I do not know if removing this file will kill the process but you can try to tie both together.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜