My target is to intercommunicate main process and its "fork" children.
Communication is done by signal delivery.
My problem appears when first child gets stuck waiting when waiting for SIGUSR1 signal.
I have no real idea why it gets stuck on that point. Evenmore if I sent signals by console, that child process seems not paying attention.
Could anybody help me?
Here comes the code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
int N = 5;
int _pipe[2];
pid_t children[5];
void main(){
pid_t parent_pid;
pid_t pid;
int i = 0;
sigset_t set;
sigfillset(&set);
parent_pid = getpid();
fprintf(stderr,"I am main process, here comes my pid %u\n",getpid());
if (0>pipe(_pipe)) fprintf(stderr,"Error when creating pipe");
//Start creating child processes
while (i < N){
pid = fork();
if (pid == 0){
close(_pipe[1]);
break;
}
else{
fprintf(stderr,"Created child with pid %u\n",pid);
children[i] = pid;
write(_pipe[1],&pid,sizeof(pid_t));
}
i = i+1;
}
i = 0;
// What main process does
if (pid>0){
close(_pipe[0]);
close(_pipe[1]);
sigdelset(&set,SIGUSR2);
sigdelset(&set,SIGTERM);
sigdelset(&set,SIGKILL);
// Main process sends signal to each child
while(i < N){
kill(children[i],SIGUSR1);
fprintf(stderr,"Sent SIGUSR1 to child %u\n",children[i]);
// .. Now just wait for SIGUSR2 arrival
sigsuspend(&set);
i = i+1;
}
}
// What children do
else{
// Wait for main process SIGUSR1 delivery
sigdelset(&set,SIGUSR1);
sigsuspend(&set);
fprintf(stderr, "SIGUSR1 arrived child %u from its father",getpid());
// Once SIGUSR1 has arrived, pipe is read N times
while((i < N) && (read(_pipe[0],&pid,sizeof(pid_t))>0)){
children[i] = pid;
i = i+1;
}
close(_pipe[0]);
// After reading pipe, a reply is sent to parent process
kill(parent_pid,SIGUSR2);
}
}
The problem most likely has to-do with the fact that the parent is sending the signals to the child processes immediately after it has forked them, and the child processes aren't blocking the signal. Thus by the time you call sigsuspend() in the child process, the signal has already been delivered to the child, and now it just sits there waiting for a signal that's never coming. You can quickly test this theory by placing a call to sleep() in the main process for a second or two before it starts sending signals. Keep in mind that as your code is structured right now, sigsuspend() won't work right without signal handlers for the signals you're waiting on ... so I suggest the following when working with signals like this:
In the parent process, block all the signals that you're planning on using for communication between the parent and child processes. You'll need to call sigprocmask() for this.
Have the parent fork the child processes
In the child processes simply call sigwait() using a signal set containing the blocked signals being used for communication ... you don't need sigsuspend() for what you're doing here.
After the parent process has sent the signals to the children, it too can call sigwait() to wait for the child process replies.
Here is an example of your code that does work: http://ideone.com/TRcqga
Related
In this example from the CSAPP book chap.8:
\#include "csapp.h"
/* WARNING: This code is buggy! \*/
void handler1(int sig)
{
int olderrno = errno;
if ((waitpid(-1, NULL, 0)) < 0)
sio_error("waitpid error");
Sio_puts("Handler reaped child\n");
Sleep(1);
errno = olderrno;
}
int main()
{
int i, n;
char buf[MAXBUF];
if (signal(SIGCHLD, handler1) == SIG_ERR)
unix_error("signal error");
/* Parent creates children */
for (i = 0; i < 3; i++) {
if (Fork() == 0) {
printf("Hello from child %d\n", (int)getpid());
exit(0);
}
}
/* Parent waits for terminal input and then processes it */
if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0)
unix_error("read");
printf("Parent processing input\n");
while (1)
;
exit(0);
}
It generates the following output:
......
Hello from child 14073
Hello from child 14074
Hello from child 14075
Handler reaped child
Handler reaped child //more than one child reaped
......
The if block used for waitpid() is used to generate a mistake that waitpid() is not able to reap all children. While I understand that waitpid() is to be put in a while() loop to ensure reaping all children, what I don't understand is that why only one waitpid() call is made, yet was able to reap more than one children(Note in the output more than one child is reaped by handler)? According to this answer: Why does waitpid in a signal handler need to loop?
waitpid() is only able to reap one child.
Thanks!
update:
this is irrelevant, but the handler is corrected in the following way(also taken from the CSAPP book):
void handler2(int sig)
{
int olderrno = errno;
while (waitpid(-1, NULL, 0) > 0) {
Sio_puts("Handler reaped child\n");
}
if (errno != ECHILD)
Sio_error("waitpid error");
Sleep(1);
errno = olderrno;
}
Running this code on my linux computer.
The signal handler you designated runs every time the signal you assigned to it (SIGCHLD in this case) is received. While it is true that waitpid is only executed once per signal receival, the handler still executes it multiple times because it gets called every time a child terminates.
Child n terminates (SIGCHLD), the handler springs into action and uses waitpid to "reap" the just exited child.
Child n+1 terminates and its behaviour follows the same as Child n. This goes on for every child there is.
There is no need to loop it as it gets called only when needed in the first place.
Edit: As pointed out below, the reason as to why the book later corrects it with the intended loop is because if multiple children send their termination signal at the same time, the handler may only end up getting one of them.
signal(7):
Standard signals do not queue. If multiple instances of a
standard signal are generated while that signal is blocked, then
only one instance of the signal is marked as pending (and the
signal will be delivered just once when it is unblocked).
Looping waitpid assures the reaping of all exited children and not just one of them as is the case right now.
Why is looping solving the issue of multiple signals?
Picture this: you are currently inside the handler, handling a SIGCHLD signal you have received and whilst you are doing that, you receive more signals from other children that have terminated in the meantime. These signals cannot queue up. By constantly looping waitpid, you are making sure that even if the handler itself can't deal with the multiple signals being sent, waitpid still picks them up as it's constantly running, rather than only running when the handler activates, which can or can't work as intended depending on whether signals have been merged or not.
waitpid still exits correctly once there are no more children to reap. It is important to understand that the loop is only there to catch signals that are sent when you are already in the signal handler and not during normal code execution as in that case the signal handler will take care of it as normal.
If you are still in doubt, try reading these two answers to your question.
How to make sure that `waitpid(-1, &stat, WNOHANG)` collect all children processes
Why does waitpid in a signal handler need to loop? (first two paragraphs)
The first one uses flags such as WNOHANG, but this only makes waitpid return immediately instead of waiting, if there is no child process ready to be reaped.
I tried to answer this question:
Write a program C that creates two children. The second child process
is blocked until the reception of the signal SIGUSR1 sent from the
parent process. While the first child process is blocked until the
reception of the signal SIGUSR2 (that will kill him) sent from the
second child process. The parent is terminated after the termination
of his children.
However the execution is not working as intended with my code below, and only the parent printfs are displayed. Can you tell me what's wrong with my code?
My code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
void this(int sig) {
printf("this is this");
}
int main() {
int pid = fork();
int pid2;
if (pid < 0) {
exit(-1);
} else if (pid == 0) {
printf("FIrst child is paused");
pause();
printf("ERror");
} else {
pid2 = fork();
if (pid2 < 0) {
exit(-2);
} else if (pid2 == 0) {
signal(SIGUSR1, &this);
printf("Second child is paused");
pause();
kill(pid,SIGUSR2);
printf("signal sent to first child");
} else {
printf("this is the parent");
kill(pid2, SIGUSR1);
printf("signal sent to second child");
wait(NULL);
exit(-3);
}
}
}
You make no provision to ensure that the parent's signal is delivered to the second child only when that child is ready for it. Because process startup takes some time, chances are good that the signal is indeed delivered sooner. In that case, the second child will be terminated (default disposition of SIGUSR1) or it will block indefinitely in pause() (if the signal is received after the handler is installed but before pauseing). In neither case will the second child signal the first.
Signal masks and signal dispositions are inherited across a fork, so you can address that by blocking SIGUSR1 in the parent before forking, and then using sigsuspend() in the child instead of pause(), which will enable you to atomically unblock the signal and start waiting for it.
The same is not an issue for the first child because you're looking for it to exercise the default disposition for SIGUSR2 (termination), and it does not matter for the specified behavior whether that happens before that child reaches or blocks in pause().
Additionally,
the parent waits only for one child, but the prompt seems to say that it must wait for both. Perhaps you dropped the second wait() because the parent was not terminating, but if so, that was a missed clue that one of the children was not terminating.
printf is not async-signal-safe, so calling it from a signal handler invokes undefined behavior.
you should put a newline at the end of your printf formats. This will make your output much more readable, and it will also ensure that the output is delivered to the screen promptly. That could end up being useful as you debug. Alternatively, use puts() instead of printf() since you are outputting only fixed strings. puts() will add a newline automatically.
The absence of newlines probably explains why the first child's output from before it pauses is never printed. If the second child were reaching the indefinite pause state then it would also explain why that child's pre-pause output was not being printed.
I am new in C. I am trying to make a shell - like program. I am currently making a signal handler, which means, when the process is running and somebody pressed ctrl + Z the process should pause and go to background while shell has to continue. The problem here is: parent process is making wait(NULL), but child is not ending the program so basically parent waits the child which is not ending the program yet. How to make it so that parent continues to work foreground. (you can see my code How to redirect signal to child process from parent process? here)
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
pid_t pid;
void send_signal(int signum){
kill(pid, signum);
}
void init_signals(){
signal(SIGINT, send_signal);
signal(SIGTSTP, send_signal);
}
int main(){
init_signals();
pid = fork();
if(pid > 0){
//Parent Process
printf("PARENT: %d\n", getpid());
waitpid(pid, NULL, WUNTRACED);
printf("Parent out of wait, i think this is what you are expecting\n");
} else {
struct sigaction act = {{0}};
act.sa_handler = send_signal;
act.sa_flags = SA_RESETHAND;
sigaction(SIGTSTP, &act, NULL);
sigaction(SIGINT, &act, NULL);
perror("sigaction ");
printf("CHILD: %d\n", getpid());
// Child Process
while(1){
usleep(300000);
}
}
return 0;
}
I think above code can serve your purpose. Let me explain it.
In your code [How to redirect signal to child process from parent process? you have handled signal and from hander context sending same signal.When you pressed Ctrl + c or Ctrl + z both parent and child receives signal. Now as per the handler code
void send_signal(int signum) {
kill(pid, signum);
}
when handler will execute in parent's context pid will be equal to child's pid so it will send signal to child but when handler runs in child context pid value will be 0, so it sends signal to whole process group i.e. parent as well as child. this make you code to run handler recursively for infinite times. Due to this you are not getting desired result.
I have modified two things to get desired result.
child context
In child context restore the signal action to the default upon entry to the signal handler so that when child receives signal for second time signal default action can be performed.
parent context
use waitpid() instead of wait().
pid_t waitpid(pid_t pid, int *status, int options);
The waitpid() system call suspends execution of the calling process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument.
`WUNTRACED` also return if a child has stopped
Due to WUNTRACED parent process will return when child will be stopped or terminated.
I hope it will serve you purpose ask me if it don't.
I need to fork two child-processes. One can receive the signal 3, print hello and send the signal 4 to the the other child process; The other can receive the signal 4, print world and send the signal 3 to the first child process.
To start, the father process will send the signal 3 to the first child process after sleeping for 3 seconds.
Then 3 seconds later, the father process will send SIGKILL to kill both of them.
I don't know how to send signals to a specific child process (I knew that we had a function kill to send signals but I don't know to use it here).
Here is my code:
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
void func(int n)
{
printf("ping\n");
// how to send signal 4 to the second process?
}
void func2(int n)
{
printf("pong\n");
// how to send signal 3 to the first process?
}
int main()
{
pid_t pid;
int i;
for(i = 0; i < 2; i++)
{
pid = fork();
if(pid == 0)
{
if(i == 0)
{
signal(3, func);
}
else
{
signal(4, func2);
}
while(1);
}
else
{
if(i == 1)
{
sleep(3);
// how to send signal 3 to the first child process?
sleep(3);
// how to kill the two children?
}
}
}
return 0;
}
you could use the popen() function to open a process by forking and opening a pipe to that process (instead of using fork() directly)
The parent knows the PID of each process so can then easily pass the pid of the second child to the first child.
The first child can use the pid and the kill()` function to pass a signal to the second child.
SO, use popen() to start the first child. use fork() to start the second child, then pass the pid from the second child to the first via the stream created with popen().
the handling of the pid value returned from the call to fork() is not being handled correctly.
The posted code is making the assumption that the call to fork() was successful... This is not a safe/valid assumption
The code also needs to check for the pid being -1 and appropriately handling that error.
when a child process completes, it should NOT sit in a while() loop but rather exit, using the exit() function.
The parent, should not just exit, as that leaves the two child processes as zombies. (zombies are very difficult to get rid of short of a system reboot.)
Rather, the parent should call wait() or even better waitpid() (and remember the child processes need to actually exit, NOT sit in a while() loop.
1) the func() and func2() should check the parameter to assure that it was the correct signal that was being processed.
2) the man page for signal() indicates that it should not be used. The man page suggest using: sigaction(),
When you fork you get the new pid. Per the kill manpage you call kill(pid_t pid, int sig); using the pid
I'm writing a program that uses fork to create child processes and count them when they're done.
How can I be sure I'm not losing signals?
what will happen if a child sends the signal while the main program still handles the previous signal? is the signal "lost"? how can I avoid this situation?
void my_prog()
{
for(i = 0; i<numberOfDirectChildrenGlobal; ++i) {
pid = fork();
if(pid > 0)//parent
//do parent thing
else if(0 == pid) //child
//do child thing
else
//exit with error
}
while(numberOfDirectChildrenGlobal > 0) {
pause(); //waiting for signal as many times as number of direct children
}
kill(getppid(),SIGUSR1);
exit(0);
}
void sigUsrHandler(int signum)
{
//re-register to SIGUSR1
signal(SIGUSR1, sigUsrHandler);
//update number of children that finished
--numberOfDirectChildrenGlobal;
}
It's recommended to use sigaction instead of signal, but in both cases it won't provide what you need. If a child sends a signal while the previous signal is still being handled, it will become a pending signal, but if more signals are sent they will be discarded (on systems that are not blocking incoming signals, the signals can be delivered before reestablishment of the handler and again resulting in missing signals). There is no workaround for this.
What one usually does is to assume that some signals are missing, and lets the handler take care of exiting children.
In your case, instead of sending a signal from your children, just let the children terminate. Once they terminate, the parent's SIGCHLD handler should be used to reap them. Using waitpid with WNOHANG option ensures that the parent will catch all the children even if they all terminate at the same time.
For example, a SIGCHLD handler that counts the number of exited children can be :
pid_t pid;
while((pid = waitpid(-1, NULL, WNOHANG)) > 0) {
nrOfChildrenHandled++;
}
To avoid this situation you can use the posix real-time signals.
Use sigaction instead of signal to register your handlers, and the delivery of the signals is assured.