Signals and Threads How do you handle signals in a threaded environment?
If a signal is sent to a threaded program, any of the threads can handle the signal.
Each thread inherits the process signal mask, but each thread has its own signal mask that can be modified with pthread_sigmask.
sigprocmask should not be used in a threaded environment, but it can be used before the threads are created.
The simplest way to handle signals in a multithreaded environment is to
have a thread dedicated to signal handling.
Issues involving signal safety can be handled by using sigwait:
The solution_server program.
This program takes one command line parameter, a port number.
It waits for connections to come in and starts a thread to handle each
connection.
For each connection, an item is read.
An item contains N 16-bit values in network byte order.
It assembles the values in an item and puts them in the solution_buffer.
The solution_buffer handles the synchronization using a semaphore.
The solution_server also keeps track of the clients that have connected
and the number of connections made by each client.
It stores this information in a client_buffer that is similar
to the solution_buffer.
The solution_server can accept SIGUSR1 signals.
When it receives such a signal, it displays information about each client
(the number of connections made) and displays the solution_buffer.
Signals are handled with a dedicated thread called print_thread
The solution_server calls handle_connection to handle a connection.
This method allocates space for a file descriptor and a client name
and passes this to a new thread, solution_thread.
solution_thread is responsible for freeing this buffer and closing the
file descriptor.
Note that solution_server cannot just pass an automatic storage buffer to the
thread as a parameter.
If the thread does not close the file descriptor, the process will eventually
run out of file descriptors.
The solution_server checks to see that the solutions it has been sent are valid.
If it did not do this, a poorly written client could insert invalid values
in the solution_buffer.