Pipes and process groups

Source code for this tidbit is available at the Linux Tidbits repo here.

We have 2 simple programs, which we shall connect via a pipe on the shell and run. The first one, gen_nums, generates 2 random numbers every second and prints them on to the console. The other program reads the output of gen_nums via a pipe is add_nums. This adds the two numbers and outputs them on to stdout.

Let’s see how a session looks like:

➜  ./gen_nums | ./add_nums 
gen_nums: PID: 11063, PGID: 11063
add_nums: PID: 11064, PGID: 11063
166
48
95
^Cadd_nums got SIGINT. Will exit...
get_nums got SIGINT. Will exit...

If you notice carefully, you’d have already seen that gen_num has the same PID and process group ID. This means that it is the process group leader. You can also see that add_nums has also been made part of the same process group ID. You can notice that when we hit Ctrl+C, both processes which handle it and exit get the signal.

The thing is that the terminal sends all the processes in the foreground process group ID the signal. That’s how it knows which all processes to send the signal to.


Posted

in

by

Discover more from Unixism

Subscribe now to keep reading and get access to the full archive.

Continue reading