Skip to content

Instantly share code, notes, and snippets.

@rubasov
Created December 7, 2012 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rubasov/4235657 to your computer and use it in GitHub Desktop.
Save rubasov/4235657 to your computer and use it in GitHub Desktop.
print the pid chain of process-parent-grandparent-... under Linux
#! /usr/bin/perl
=head1 NAME
pidof-ancestors - print the pid chain of process-parent-grandparent-...
=head1 SYNOPSIS
pidof-ancestors PID
=head1 DESCRIPTION
Prints a list of process IDs, one per line. The first is the pid given
as an argument (in case it exists), the second is the pid of its parent,
grandparent, and so on. The last one is typically pid 1, i.e. init.
Exits early with non-zero if it can't find the pid given or the parent
of any process in the chain.
The collection of information is not atomic, the processes we look for
may die or get reparented before we find them.
=head1 SEE ALSO
ps(1)
=head1 AUTHOR
Copyright 2012 by Bence Romsics <rubasov@gmail.com>
Licensed under the GNU GPL.
=cut
use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
sub _usage_and_exit {
my %opt = @_;
pod2usage(
-noperldoc => 1,
-verbose => 99,
-exitval => defined $opt{help} && $opt{help} ? 0 : 1,
-output => defined $opt{help} && $opt{help} ? \*STDOUT : \*STDERR,
);
}
my %opt;
my $rv = GetOptions( \%opt, 'help|h', );
my $pid = shift;
_usage_and_exit( help => $opt{help} )
if not $rv
or defined $opt{help}
or not defined $pid
or $pid !~ /^\d+$/
or $pid < 1
or @ARGV;
while ( $pid > 0 ) {
open my $stat_fh, "<", "/proc/$pid/stat"
or die "no such pid: $pid\n";
my $ppid = ( split /\s+/, <$stat_fh> )[3];
close $stat_fh;
print $pid, "\n";
$pid = $ppid;
}
@danielg4
Copy link

Here's the fix you suggested.

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