#!/usr/bin/perl
#Written by Jarett Stevens
#inspired by http://www.commandlinefu.com/commands/view/5450/intercept-stdoutstderr-of-another-process

use warnings ;
use strict ;
$| = 1 ;

my @PID_FD ; 
my $FD_SET ;
my $CHARS ;

if ( $#ARGV != 0 ) {
	printf(STDERR "usage: %s <pid>\n",$0) ;
	exit(1) ;
}

unless (@PID_FD = </proc/$ARGV[0]/fd/*>) {
	printf(STDERR "cannot access pid: %s\n",$ARGV[0]) ;
	exit(1) ;
}

for (@PID_FD) {
	if (readlink($_) =~ m/\/dev\/pts|\/dev\/tty/) {
		$_ =~ s/^.*\/// ;
		$FD_SET .= "$_," ;
	}
}

open(STRACE, "strace -ff -e read=$FD_SET -e write=$FD_SET -s 1024 -p $ARGV[0] 2>&1 |") or die "could not locate/execute strace" ;

while (<STRACE>) {
	if ($_ =~ m/^ \|/ ) {
		$CHARS = substr($_, 9, 50) ;
		$CHARS =~ s/ //g ;
		print pack("H*", "$CHARS") ;
	}	
}

