Created
January 27, 2020 05:26
-
-
Save firelizzard18/a17befadf32f8da94ff43ccd45811c30 to your computer and use it in GitHub Desktop.
Find PID on other end of pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
pid=$$ | |
pgid=$(ps -o pgid= -p $pid) | |
# list files opened by process group | |
lsof=$(bash -c 'echo $$; exec lsof -g '"$pgid") | |
# get pid of lsof | |
lpid=$(echo "$lsof" | head -1) | |
# filter for pipes, exclude files opened by lsof | |
lsof=$(echo "$lsof" | awk '$6=="PIPE" && $2!="'"$lpid"'" {print}') | |
# find own stdin device | |
pipe=$(echo "$lsof" | awk '$5=="0" && $2=="'"$pid"'" {print substr($9,3)}') | |
# find processes with stdout connected to own stdin | |
pids=$(echo "$lsof" | awk '$5=="1" && $7=="'"$pipe"'" {print $2}') | |
# list full command for first process | |
for p in $pids; do | |
ps -p $p -o command= 2>/dev/null && break | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Derived from https://superuser.com/a/244427