主 shell 退出后 >(进程) 收到哪个信号?

主 shell 退出后 >(进程) 收到哪个信号?

这是一个 Zshell 问题,尽管 Bash 如果它具有 >(command) 语法(即此类进程替换),也可以提示解决方案。这个非常基本的代码解释了所有内容:

% fun() {
   setopt localtraps
   trap "echo waiting >> /tmp/out; sleep 2; echo bye >> /tmp/out; exit 1;" EXIT
   echo "My PID: $sysparams[pid]"  # needs zsh/system module
   repeat 1000; do
      read -r -t 1 line
   done
}

% exec {MYFD}> >(fun)
% exit

以上工作 - fun() 将接收陷阱,两条消息将出现在 /tmp/out 中,“exit 1”将关闭进程。

我的问题:“EXIT”可以用一些实际信号代替吗?我尝试过 PIPE、HUP、INT、TERM,但都不起作用。

答案1

你的代码并不能解释一切。我不知道你想做什么。不过,我可以回答你标题中的问题:>(…)当主 shell 退出时,进程没有收到信号。它退出是因为它到达了脚本的末尾,此时它运行EXIT陷阱直到执行exit内置函数。

如果您认为脚本会被提前终止,因为您认为每个read -t 1调用将花费一秒钟:不,它们不会,它们会在父进程退出后立即返回。当父进程退出时,子readshell 中的调用会尝试从关闭的管道中读取数据,并且底层read系统调用会立即返回,但没有可用数据。

答案2

bash根据和的手册zsh,是的,您确实可以发出trap任何信号。

bash:

   trap [-lp] [[arg] sigspec ...]
          The command arg is to be read and executed when the shell receives signal(s) sigspec.  If arg is absent (and there is a single sigspec) or  -,  each  specified  signal  is
          reset  to  its  original disposition (the value it had upon entrance to the shell).  If arg is the null string the signal specified by each sigspec is ignored by the shell
          and by the commands it invokes.  If arg is not present and -p has been supplied, then the trap commands associated with each sigspec are displayed.  If  no  arguments  are
          supplied  or  if  only -p is given, trap prints the list of commands associated with each signal.  The -l option causes the shell to print a list of signal names and their
          corresponding numbers.  Each sigspec is either a signal name defined in <signal.h>, or a signal number.  Signal names are case insensitive and the SIG prefix is  optional.

zsh:

   trap [ arg ] [ sig ... ]
          arg is a series of commands (usually quoted to protect it from immediate evaluation by the shell) to be read and executed when the shell receives any of the signals speci-
          fied by one or more sig args.  Each sig can be given as a number, or as the name of a signal either with or without the string SIG in front (e.g. 1, HUP,  and  SIGHUP  are
          all the same signal).

相关内容