2

If a program PROG is invoked with pipes,

progA | progB | PROG | progC ...

Is there a way for it to tell in what context it was invoked - i.e., from/to what other programs (A, B, C...) it is receiving or sending piped output?

I'm mostly interested in the immediate predecessor to PROG (in the example above, progB), but am also curious about the more general question.

user2141650
  • 2,827
  • 1
  • 15
  • 23
  • It can be done, yes, but not easily and (as l0b0 says) not portably. – Kevin Jun 25 '13 at 14:17
  • What's the larger or underlying problem, such that this is something you think you need? – Charles Duffy Jun 25 '13 at 14:18
  • @CharlesDuffy : `PROG` is a little like [grcat/grc](http://kassiopeia.juls.savba.sk/~garabik/software/grc/README.txt), and ideally would "colorize" (not actually what it does, but not _relevantly_ different either) based on what it knows about previous programs rather than file extensions. – user2141650 Jun 25 '13 at 14:38
  • @user2141650 Your safest approach is to require the caller to indicate the input type to each component of the pipeline. Not much fun, but anything else is going to be unportable, fragile guesswork. – Charles Duffy Jun 25 '13 at 15:26

2 Answers2

2

If you're on Linux you can use the /proc filesystem to check how commands communicate over pipes. However, this is not really portable.

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • I'll wait to see if any more portable solutions come up, but otherwise your shell script was very helpful. It looks as though it won't work if the previous program has exited. Unfortunate, since if you pipe a program to another that has e.g. a bus error, you'll get an error that displays all the elements of the pipe whether or not they exited. If only the kernel could expose what it evidently knows... – user2141650 Jun 26 '13 at 15:12
  • Thanks for the tip. I also really want to know the answer to your question to continue development of the script. – l0b0 Jun 26 '13 at 15:18
2

You can use ps to show all the processes which have the same parent. For example, if PROG has pid PID, on Linux you can do:

ps --ppid $(ps -o ppid= $PID)

to get a listing of all the commands in the pipeline. (Actually, you'll get all the commands that are children of the shell that invoked the pipeline, which may be sufficient. You can check the process group of each to determine which ones are actually in the pipeline.) The order in which they print is not necessarily the order they appear in the pipe, put you can look in /proc/pid/fd to see the inode of each process' inputs to determine how they line up.

William Pursell
  • 204,365
  • 48
  • 270
  • 300