Mohamad Zein
Mohamad Zein

Reputation: 777

child process kill itself after 3 seconds in fork

I have a fork function that creates a child process and a parent process

I would like the child process to kill itself as soon as 3 seconds passes, using the kill(child, SIGKILL) function, that means withoutt using the exit() function. However I am not sure of the implementation. I tried using the kill function signal right after the while loop end, but it does not kill the child.

I tried to put it at the end of the main function, but it kills the child before 3 seconds passes

I tried to put it in a function that is called as soon as the while loop ends, but it did not kill the child

How can I do this with a better implementation that actually works ?

here is my code with comments available:

int main()
{
    pid_t pid;
    int seconds = 3;
    int child;

    pid = fork();
    int i = 0;



    if(pid == 0)          //this is the child
    {
        child = getpid();

        while( i <= seconds)
        {
            cout << " second " << i << endl;
            sleep(1);
            i++;

        }
        killChild(child);     //function called after 3 seconds passes

    }

    else if(pid < 0)        //error statement
    {
        cout << " we have an error " << endl;
    }

    else                //parent if pid > 0
    {
        cout << " I am the parent " << endl;
        sleep(1);

    }

    //kill(child, SIGKILL)  placing it here will kill child before seconds passes

}


void killChild(int child)       //function to kill child (NOT KILLING IT)
{
    kill(child, SIGKILL);
}

Upvotes: 0

Views: 3943

Answers (1)

Aisha Javed
Aisha Javed

Reputation: 169

 void killChild(int sigNum)//Argument here is signal number
    {
        kill(getpid(), SIGKILL);
    }  


  int main()
    {
        pid_t pid;
        int child;
        pid = fork();

        if(pid == 0)//this is the child
        {
            signal(SIGALRM,killchild)
            child = getpid();
            alarm(3); //set alarm for 3 seconds
            while(1); //continue to loop until 3 seconds passed
        }

        else if(pid < 0)//error statement
        {
            cout << " we have an error " << endl;
        }

        else//parent if pid > 0
        {
            cout << " I am the parent " << endl;
        }
    }

   After 3 seconds, alarm() function will generate SIGALRM and on this signal egneration, your killchild() function will be called and kill child. 

Hope this helps!

Upvotes: 3

Related Questions