I'm trying to do an assignment for one of my classes and no professors/fellow classmates are getting back to me. So before you answer, please don't give me any exact answers! Only explanations!
What I have to do is write a c program (timeout.c) that takes in two command line arguments, W and T, where W is the amount of time in seconds the child process should take before exiting, and T is the amount of time the parent process should wait for the child process, before killing the child process and printing out a "Time Out" message. Basically, if W > T, there should be a timeout. Otherwise, the child should finish its work and then no timeout message is printed.
What I wanted to do was just have the parent process sleep for T seconds, and then kill the child process and print out the timeout, however printing out the timeout message would happen no in both cases. How do I check to see that the child process is terminated? I was told to use alarm() for this, however I have no idea of what use that function would serve.
Here's my code in case anyone wants to take a look:
void handler (int sig) {
return;
}
int main(int argc, char* argv[]){
if (argc != 3) {
printf ("Please enter values W and T, where W\n");
printf ("is the number of seconds the child\n");
printf ("should do work for, and T is the number\n");
printf ("of seconds the parent process should wait.\n");
printf ("-------------------------------------------\n");
printf ("./executable <W> <T>\n");
}
pid_t pid;
unsigned int work_seconds = (unsigned int) atoi(argv[1]);
unsigned int wait_seconds = (unsigned int) atoi(argv[2]);
if ((pid = fork()) == 0) {
/* child code */
sleep(work_seconds);
printf("Child done.\n");
exit(0);
}
sleep(wait_seconds);
kill(pid, SIGKILL);
printf("Time out.");
exit(0);
}
Although waitpid would get you the return status of the child, its default usage would force parent to wait until the child terminates.
But your requirement (if i understood correctly) only wants parent to wait for a certain time, alarm() can be used to do that.
Then, you should use waitpid() with a specific option that returns immediately if the child has not exited yet (study the api's parameters). So if the child didn't exit, you could kill it, else you already receive its return status.
You want the timeout program to stop more or less as soon as the command finishes, so if you say timeout -t 1000 sleep 1 the protecting program stops after about 1 second, not after 1000 seconds.
The way to do that is to set an alarm of some sort — classically, with the alarm() system call and a signal handler for SIGALRM — and then have the main process execute wait() or waitpid() so that when the child dies, it wakes up and collects the corpse. If the parent process gets the alarm signal, it can print its message and send death threats of some sort to its child. It might be sensible to try SIGTERM and/or SIGHUP before resorting to SIGKILL; the SIGTERM and SIGHUP signals give the errant child a chance to clean up whereas SIGKILL does not.
If you know how to manage signals, you could catch SIGALRM and SIGCHLD in your parent process. SIGCHLD will be raised when the client terminates, and SIGALRM when the timer expires. If the first raised signal is SIGALRM, the timeout expired, otherwise, if the first SIGNAL that the parent catches is SIGCHLD, the child has stopped before the expiration of the timeout.
wait() or waitpid() would still be necessary to collect the terminated child.
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 have made this program and the output so far doesn't make much sense to me. Can someone please explain what is going on?
void handler1a(int x){
printf("A\n");
}
int main(){
signal(SIGUSR1, handler1a);
int p = fork();
if(p==0)
{
sleep(5);
printf("L \n");
}
else
{
kill(0,SIGUSR1);
kill(0,SIGUSR1);
kill(0,SIGUSR1);
//kill(0,SIGUSR1);
wait(NULL);
}
}
With 3 kill signals, my output is- 5A and 1L. With 2 kill signals, the output is- 4A and 1L. With 4 kill signals, output is- 6A and 1L. It seems like upto 2 kill signals, both parent and child process are using my custom handler but somehow one of them isn't using the handler or isn't getting the kill signal after receiving the signal it twice already (it would explain why only a single A is printed when I add another kill system call after 2 kill system calls).
Signals aren't queued. So if you send the same signal to a process multiple times, it may get processed any number of times from 1 to the number of times you sent the signal.
Or, to put it another way, for each combination of process and signal, the signal can be in the signaled state. If you send a signal to a process when that process is already in the signaled state for that signal, nothing happens.
A process cannot have two SIGUSR1 signals pending. Either SIGUSR1 is pending or it isn't.
Here kill is called by the parent process P with 0 as its pid value which means that all the processes in its group (P itself, as well as the child C) will get the signal and the same custom signal handler will be used to process it.
If you are sending multiple signals to the process C that are of same type (SIGUSR1 here), they will not be queued because that signal will be blocked until the first one received is handled, and they will be discarded.
Only when the signal handler for C returns, C is ready to process the signal again. This explains why there are fewer "A"s in the output from C's invocation of the handler.
You can see which process has called the handler by adding printf("A %d\n", getpid()) inside the handler.
I read in an ebook that waitpid(-1, &status, WNOHANG) should be put under a while loop so that if multiple child process exits simultaniously , they are all get reaped.
I tried this concept by creating and terminating 2 child processes at the same time and reaping it by waitpid WITHOUT using loop. And the are all been reaped .
Question is , is it very necessary to put waitpid under a loop ?
#include<stdio.h>
#include<sys/wait.h>
#include<signal.h>
int func(int pid)
{
if(pid < 0)
return 0;
func(pid - 1);
}
void sighand(int sig)
{
int i=45;
int stat, pid;
printf("Signal caught\n");
//while( (
pid = waitpid(-1, &stat, WNOHANG);
//) > 0){
printf("Reaped process %d----%d\n", pid, stat);
func(pid);
}
int main()
{
int i;
signal(SIGCHLD, sighand);
pid_t child_id;
if( (child_id=fork()) == 0 ) //child process
{
printf("Child ID %d\n",getpid());
printf("child exiting ...\n");
}
else
{
if( (child_id=fork()) == 0 ) //child process
{
printf("Child ID %d\n",getpid());
printf("child exiting ...\n");
}
else
{
printf("------------Parent with ID %d \n",getpid());
printf("parent exiting ....\n");
sleep(10);
sleep(10);
}
}
}
Yes.
Okay, I'll elaborate.
Each call to waitpid reaps one, and only one, child. Since you put the call inside the signal handler, there is no guarantee that the second child will exit before you finish executing the first signal handler. For two processes that is okay (the pending signal will be handled when you finish), but for more, it might be that two children will finish while you're still handling another one. Since signals are not queued, you will miss a notification.
If that happens, you will not reap all children. To avoid that problem, the loop recommendation was introduced. If you want to see it happen, try running your test with more children. The more you run, the more likely you'll see the problem.
With that out of the way, let's talk about some other issues.
First, your signal handler calls printf. That is a major no-no. Very few functions are signal handler safe, and printf definitely isn't one. You can try and make your signal handler safer, but a much saner approach is to put in a signal handler that merely sets a flag, and then doing the actual wait call in your main program's flow.
Since your main flow is, typically, to call select/epoll, make sure to look up pselect and epoll_pwait, and to understand what they do and why they are needed.
Even better (but Linux specific), look up signalfd. You might not need the signal handler at all.
Edited to add:
The loop does not change the fact that two signal deliveries are merged into one handler call. What it does do is that this one call handles all pending events.
Of course, once that's the case, you must use WNOHANG. The same artifacts that cause signals to be merged might also cause you to handle an event for which a signal is yet to be delivered.
If that happens, then once your first signal handler exists, it will get called again. This time, however, there will be no pending events (as the events were already extracted by the loop). If you do not specify WNOHANG, your wait block, and the program will be stuck indefinitely.
I need to create n children from the same parent, and have them running while the parent asks infinitely for a signal to send to some child. I made the parent create those n children, but they finished executing, so I made them enter a while(1) loop. The problem is, when I try to kill any child, it becomes a zombie process instead of actually terminating its execution. I'm guessing that's because the parent is still waiting for the children to terminate execution and they don't send the exit status. So... First of all, do I really need to make the children enter an infinite while loop to make them be running while the parent is asking for the signals? If I do, how do I avoid this "never terminating execution" problem? I need to find a way for the children to exit that while loop and send the actual "finished execution" signal since I think I can't use wait() because the children never actually finish running, they are just terminated by the parent.
Thanks.
PS: Running in Linux. This is my code
int main(){
int i;
pid_t parent = getpid();
pid_t pid[4];
printf("parent with pid %d\n", parent);
for(i = 0; i < 5; i++){
pid[i] = fork();
if(pid[i] < 0){
perror("Error in fork.");
exit(1);
} else if(pid[i] == 0 && getppid() == padre) {
printf("Number: %d pid %d, parent: %d\n", i, getpid(), getppid());
while(1);
}
}
if(getpid() == padre){
while(1){
printf("Enter pid and signal:\n");
int x, y;
scanf("%d", &x); // pid
scanf("%d", &y); // signal
printf("you did: kill(%d, %d)\n", x, y);
kill(x, y);
}
}
return 0;
}
EDIT:
Final code with answer implemented: https://github.com/sebasura/sistope
The problem is, when I try to kill any child, it becomes a zombie process instead of actually terminating its execution.
Well, yes and no. Becoming a zombie is normally what happens when a process terminates, until that process is collected by its parent. A zombie takes up a bit of space in the process table, but it is not running, and therefore consumes no CPU.
I'm guessing that's because the parent is still waiting for the children to terminate execution and they don't send the exit status.
No, it's because kill() just sends a signal. You need to use one of the wait() functions -- perhaps waitpid() -- to actually collect the terminated child.
So... First of all, do I really need to make the children enter an infinite while loop to make them be running while the parent is asking for the signals?
No. The child can use sigwait() or one of its variants to wait for a signal from a designated set, or pause() to suspend execution pending receipt of any signal that terminates the process or triggers a signal handler function. Note, however, that there are some signals that by default do neither of those, so sigwait() is probably the better alternative.
If I do, how do I avoid this "never terminating execution" problem?
The child must terminate as a result of receiving the signal. That's already happening for you, because the children are becoming zombies. With your present code it may depend on which signal you send, however, for there are some whose default handling does not terminate the process.
Thank you everyone, I did it.
I used pause() instead of while(1).
And after the kill, I used this:
int state;
waitpid(pid, &state, 0);
This is part of a homework so I will upload the code after the due date so they don't penalize me for sharing it or something.
Thanks again.
EDIT:
Here is the final code https://github.com/sebasura/sistope
So I'm trying to implement a signal handler for the SIGTSTP signal in a child process.
Basically what I'm trying to achieve is this:
Start child Process
Make the parent wait on the child process
call Sleep on the Child process for x seconds.
Before the sleep finishes execution, I want to send a Ctrl+Z signal.
This signal should stop the child process, but resume the parent
process. The parent process should then know the process id of the
stopped process.
I run it using the command: ./testsig sleep 10
This is my code so far:
#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
#include<string.h>
volatile sig_atomic_t last_proc_stopped;
volatile sig_atomic_t parent_proc_id;
void handle_stp(int signum)
{
if(getpid()==parent_proc_id)
{
kill(parent_proc_id,SIGCONT);
signal(SIGTSTP,handle_stp);
}
else
{
last_proc_stopped=getpid();
kill(parent_proc_id,SIGCONT);
}
}
void main(int argc, char *argv[])
{
int childid=0,status;
signal(SIGTSTP,SIG_IGN);
parent_proc_id=getpid();
childid=fork();
if(childid>=0)
{
if(childid==0)//child
{
signal(SIGTSTP,handle_stp);
strcpy(argv[0],argv[1]);
strcpy(argv[1],argv[2]);
argv[2]=NULL;
printf("Passing %s %s %s\n",argv[0],argv[1],argv[2]);
execvp(argv[0],argv);
}
else
{
wait(&status);
printf("Last Proc Stopped:%d\n",last_proc_stopped);
}
}
else
{
printf("fork failed\n");
}
}
Currently, it seems like ctrl+Z has some kind of effect (but definitely not the one I want!)
When I hit ctrl+Z in the middle of the child executing sleep, the cursor continues to blink for the remainder of the (in my case 10) seconds, but control does not reach the parent process.
Without hitting ctrl+Z, control returns to the parent as expected.
What am I doing wrong?
I have seen this answer as well, but I'm not really able to understand it:
After suspending child process with SIGTSTP, shell not responding
You have two processes:
The parent, which ignores the signal,
The child, which sets a handler, then execs another process - this will clear the code of the signal handler from the memory (the executed program will be loaded in place of the calling process), therefore will also clear the signal settings as well. So, your signal handler function will never be called. Is it possible to signal handler to survive after “exec”?
What you could do to achieve your goal?
The parent should ignore the signal,
The child should leave the default signal handling (which stops it),
The parent should use waitpid() to see if the child process exited or was stopped, and act accordingly (this involves actually killing the stopped child process).