2

On sh or bash, how do I exit the first process in a pipe when the second one has exited?

I was using the following to get input from the network:

$ nc -l 1234 | myprog

myprog exited due to an internal cause but nc continues to live. Is it possible to stop nc also?

r.v
  • 4,697
  • 6
  • 35
  • 57

1 Answers1

1

In bash you can fork process with & control operator and get the pid of child reading $!. So, the simplest solution could be

$ ( nc -l 1234 & echo $! > /tmp/myprog_kill_pid ) | myprog; kill $(</tmp/myprog_kill_pid); rm /tmp/myprog_kill_pid

Of course, this is not very nice and not suitable for multiple running instances... but you can start from this.

pmod
  • 10,450
  • 1
  • 37
  • 50
  • I did a workaround to my specific problem but thanks for telling how to fork using &. – r.v Mar 27 '14 at 22:09