Prachi Rajesh Jansari
Prachi Rajesh Jansari

Reputation: 25

C programming , using alarm

I am trying to just work around different modification of program. I have a process and the parent gets killed after alarm signal goes on The child still runs an infinite loop, since the alarm is in main it does not get affected The program does not terminate at all I am trying to include kill signal so i can have the child killed after sometime as ctrl-c does not work

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(){  
    alarm(4);   //alarm in 4 seconds and terminates the program 

    int pid=fork();    //forks a child
    //if we keep the kill signal here it creates child kills it and goes to parent process
    while(1){
        if(pid==0)
            printf("I am the child \n");    //alarm clock does not effect the child process 
        else  //parent process 
            printf("I am the parent, child pid=%d\n", pid);  //this after alarm clock terminates the program
    // if we add "kill(pid, SIGKILL), doesnt even fork the child and kills it
        sleep(1);
        //kill(pid, SIGKILL); would run the child process and then kill it 
    }
}

Trying to get a little understanding on how can i kill child in this process after some time

Upvotes: 1

Views: 1977

Answers (1)

Fred Larson
Fred Larson

Reputation: 62113

Use a signal handler for your alarm. In that handler, kill() the child process and wait() for it to terminate.

For example:

#define _POSIX_SOURCE
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

pid_t kill_pid = -1;
int done_flag = 0;

void handle_alarm(pid_t sig)
{
    if (sig == SIGALRM && kill_pid >= 0)
    {
        kill(kill_pid, SIGTERM);
        int status;
        wait(&status);
        done_flag = 1;
    }
}

int main()
{
    alarm(4);   //alarm in 4 seconds and terminates the program

    pid_t pid = fork();    //forks a child
    if (pid == 0)
    {
        while (1)
        {
            printf("I am the child \n");
            sleep(1);
        }
    }
    else
    { //parent process
        kill_pid = pid;
        signal(SIGALRM, handle_alarm);

        while (!done_flag)
        {
            printf("I am the parent, child pid=%d\n", pid);
            sleep(1);
        }

        printf("Child has been terminated, parent is complete.\n");
    }
}

You could put a signal handler in the child process and make it terminate more gracefully. I've used SIGTERM here, which you can handle. SIGKILL cannot be handled by your program.

Upvotes: 1

Related Questions