Skip to content

Instantly share code, notes, and snippets.

@venam
Created June 5, 2021 12:31
Show Gist options
  • Save venam/5b8eb5f3c6e22793fbfcb3d75abc10da to your computer and use it in GitHub Desktop.
Save venam/5b8eb5f3c6e22793fbfcb3d75abc10da to your computer and use it in GitHub Desktop.
Script to list master/slave pseudoterminal ends on Linux
use strict;
use warnings;
print "MASTER\tSLAVES\n";
my $pid = -1;
for my $master_end (qx#lsof -F pcf /dev/ptmx#) {
chomp $master_end;
if ($master_end =~ /p.*/) {
print "\n" if $pid>0;
$pid = substr($master_end, 1);
print "$pid,";
} elsif ($master_end =~ /c.*/) {
print substr($master_end, 1)."\t";
}
elsif ($master_end =~ /f.*/) {
# a file descriptor for current pid
my $fd = substr($master_end, 1);
readfile("/proc/$pid/fdinfo/$fd") =~ /^tty-index:\s*(\d+)$/m;
my $slave_processes = qx#ps -o "%p,%c" -t pts/$1#;
$slave_processes =~ s/^(?:.*\n)//;
$slave_processes =~ s/^\s*//;
$slave_processes =~ s/\n/\t/g;
print "$slave_processes";
}
}
sub readfile { local $/; my $h; open $h, '<', shift and <$h> }
print "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment