Search code examples
processzshpid

Is it possible to get pid of first command (not background)? Zsh, not bash


I have in zsh: (sleep 100;program1 & another program & another)&

How to get PID of 'sleep' process (I need to kill it)? $! - returns pid not of sleep process jobs -p - also useless here

killall -9 sleep -useless, because it will kill all sleep processes, not only this.


Solution

  • One option is to print the pid from sleep from within the set of commands. This can be done by backgrounding the sleep process, getting the pid with $!, and then using wait to block until it exits.

    % (sleep 100 &; print sleep_pid:$!; wait $!; print cmd1 && print cmd2) &
    [1] 18055
    sleep_pid:18056
    % kill 18056
    cmd1
    cmd2
    [1]  + done ( sleep 100 & print sleep_pid:$!; wait $!; print cmd1 && print cmd2; )
    %
    

    If you need to access the pid programmatically, you can write it to a temp file or a named pipe.