Brky
Brky

Reputation: 59

Fork and kill in C++ crashes ubuntu

i have problem with small piece of my code.

void setTimeout(int time)
{
    if (fork() == 0) {
        pid_t id = getppid();
        sleep(time);
        if(kill(id, 0) == ESRCH)
            return;
        cerr << "Time out!" << endl;
        kill(id, TIMEOUT);
        return;
    }
}

When the parent process is running and I don't need to kill him, nothing happens and it close as it should, but if parent process ends before timeout, ubuntu crashes.

Thanks for your time.

Upvotes: 1

Views: 152

Answers (1)

catnip
catnip

Reputation: 25388

After the parent process terminates, getppid will return the process id of the shell that launched it. So you are killing the shell, which is why you drop to the login screen.

See also:

getppid() not returning parent's pid

Upvotes: 2

Related Questions