In my C program, I want to get the PID of the process, send a SIGSTOP to that and wait until a SIGCONT arrives from another terminal. So, the procedure looks like
int pid_t = getpid();
printf("PID %d has been stopped\n", pid_t);
STOP(pid_t);
while (not_received_CONT(pid_t))
;
// continue the program
How can I complete that?
CodePudding user response:
What you're writing doesn't make sense. When you stop the process, there is no more instructions being processed in the program and as such there is no while
loop to wait for receiving the continuation.
If you check man 7 signal
you can see that only one signal currently (in Linux) causes continuation of a process: SIGCONT
, hence its not technically necessary to process a while loop check if you didn't get a continuation -- UNLESS you've got a situation where a number of signals are pending and you're trying to determine that.
You can rewrite your code implicitly to be:
int pid = getpid();
printf("PID %d has been stopped\n", pid);
kill(pid, SIGSTOP);
/* Process implicitly continues here, no while needed */
There are multiple vectors in Linux to manage signal handling which may not necessarily be portable.
There is the traditional signal/sigaction
method of catching signals and invoking function calls on receipt of the signal. This can come with some unexpected caveats if you aren't careful.
Another way you can manage signals is the use of sigwait
, you block the signal with sigprocmask
and can consume signals in a safe fashion using sigwait
to consume the signal at some controlled point in your process.
Finally you can do similar to sigwait
with a signalfd
. The main difference between it and sigwait
being you can poll
the FD to determine its readiness (a signal is received) then read
the FD to consume the signals. This makes it a very nice way to manage signals in event driven programs.