Reputation: 63
I am creating a relatively simple multiple process program to learn about signals and signal handling in Linux using C. I have several processes handling signals (I use sigaction to assign handlers) that are sent to all processes in the process group and one tracking process that displays some information after a certain number of signals are detected.
My question is this. How do I reliably display console output from the tracking process? This process needs to display the current number of signals detected and I know printf() isn't good to call from a signal handler. I know I can use write(), but I am not sure I can put variable values into this to display, and I think this system call can be interrupted by signals.
Could you give me a simple example with 3 processes (one generating the signal (parent), 1 handling the signal (child 1) and one reporting info on the signals (child 2)), or explain how this reporter process should handle the output with values of global shared variables?
Thanks
Upvotes: 0
Views: 433
Reputation: 753990
See How to avoid using printf() in a signal handler? for some information about what can be done in a signal handler.
I can't give you a 'simple' example for your 3 process request because the scenario you outline is incredibly complex — how on earth is the third process going to know about what signals the first process sent to the second process? Signals are very crude; there is very little information available other than 'a signal was sent' (slightly more if you use the sa_sigaction
member of the struct sigaction
and SA_SIGINFO
flag when calling the sigaction()
function). For most practical purposes, what you ask for can't be done.
If you're going to get close to your scenario, then maybe the method is to set up a shared memory segment in the parent which both children have access to. The second child (signal receiver) can then copy information into the shared memory when it receives a signal, while the third child copies the information out of shared memory and writes it. You'll need to look to see what coordinating functions (if any) are available to a signal handler function — the x-ref'd question has answers which cover this point (and the answer looks like 'none', or only crude ones like open()
or mkdir()
). Curiously, the POSIX standard does not list function such as strcpy()
or memcpy()
as signal-safe.
As to 'how to reliably display console output', what is your process going to do while waiting for signals to arrive? You can arrange for the signal handler to set a flag, and the looping code can arrange to check the flag, format and write the data (with standard I/O even; this isn't in a signal handler any more), before going back to waiting for the next signal to arrive.
Upvotes: 1