Joe
Joe

Reputation: 129

In a basic Shell Program in C, how to exit all processes associated with a parent?

I am writing a basic shell program for a university assignment, and i need to test for when the user enters the string "exit". When this happens the program should quit.

I can test for this successfully, but if i have forked new processes that have dealt with an strerror in my program, i have to keep entering exit for however many active processes are running at that current time.

Is there a way of exiting all associated processes with a program under this condition?

Cheers.

Upvotes: 2

Views: 3006

Answers (1)

hexasoft
hexasoft

Reputation: 677

As said in comments, you should not spawn interactive processes in the background (at least how your shell and your command will handle the only stdin?).

Also as a shell you should keep track of all spawned processes (in background) so that you are able to catch their return code, as done in sh/bash (at least). For exemple in bash:

> sleep 1 &
[1] 8215
>
(1 sec later)
[1]+  Terminated      sleep 1

So if you have the list of existing children you can send SIGINT/SIGKILL to all of them.

Whatever if you really want to be sure to kill everyone you should use process group (PG) killing. Using kill() function with PID=0 sends the kill signal to all processes in the same process group than you. So you can start your shell by setting a new process group (to be sure to not kill something else), and this PG will be inherited by your children (appart if a child set a new PG of course).

This would looks like:

// at the begining of your main code
// try to get a new process group for me
x = setpgid(0,0);
if (x == -1) {
  perror("setpgid");
  exit(1);
}
(…)
// here you're about to exit from main, just kill
// all members of your group
kill(0, SIGINT);  // send an INT signal
kill(0, SIGKILL); // paranoid: if a child catch INT it will get a KILL

// now you can exit, but you're probably dead 'cause you
// also receive the SIGINT. If you want to survive you have to
// catch SIGINT, but you will not catch KILL whatever

If it is needed for you to survive the kill you may catch the signal using signal() or better sigaction() so that you will not be killed and so able to perform other before-exit actions.

Upvotes: 2

Related Questions