So this is the problem im having right now, I've created 2 different programs (1 will be managing the other, while the other will be executed multiple times). The programs will be communicating back and forth via signals. My question is, is it possible (and how) to get the process id of the program sending the signal. My programs use signal() to catch signals and kill() to send them.
Although signal() is in standard C library, this function is not portable, its behavior depending on the system. Better use sigaction() which is POSIX.1.
Here is an example of how to use sigaction with a handler void h(int sig) :
int mysignal (int sig, void (*h)(int), int options)
{
int r;
struct sigaction s;
s.sa_handler = h;
sigemptyset (&s.sa_mask);
s.sa_flags = options;
r = sigaction (sig, &s, NULL);
if (r < 0) perror (__func__);
return r;
}
options are described in man sigaction. A good choice is options=SA_RESTART.
To know the PID of the process which sent a signal, set options=SA_SIGINFO, and use a sa_sigaction callback instead of sa_handler; it will receive a siginfo_t struct, having a si_pid field. You can associate a data to the signal using sigqueue.
Generally speaking, using signals is a bad idea to communicate in a safe manner (when n signals are sent, only the first will have a chance to be delivered; there is no hook to associate other datas; the available user signals are only two). Better use pipes, named pipes or sockets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With