Skip to content

Instantly share code, notes, and snippets.

@firelizzard18
Created January 27, 2020 05:26
Show Gist options
  • Save firelizzard18/a17befadf32f8da94ff43ccd45811c30 to your computer and use it in GitHub Desktop.
Save firelizzard18/a17befadf32f8da94ff43ccd45811c30 to your computer and use it in GitHub Desktop.
Find PID on other end of pipe
#!/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
@firelizzard18
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment