0

I am trying to implement my own shell, and I don't figure out how to stop a function that it is running in foreground, if I get a SIGINT signal.

When this function is in background, it's easy, I only have to create a son, and he will run the function:

(...)
int pid = fork();
if (pid == 0){
  signal(SIGINT, killProcess)
  function();
}
(...)

And in another part:

void killProcess(int num_signal){
   kill(getpid(), SIGKILL);
}

But this doesn't work in foreground, because if the function tries to execute "cd", for example, it will be the son the one that will change it's directory, not the shell itself.

The function is not a loop, so I cannot use a variable to stop it. It is a function that executes orders, like "cd", "find",...

Is it possible to stop/terminate only the function, instead of the whole shell?

Thank you.

Homer
  • 85
  • 7
  • 1
    Using SIGKILL indicates problems; it is a desperation measure, not a routine signal to use. You can't usefully run `cd` in a child process of the shell if it is supposed to change the parent shell's current directory (as you seem to be aware). So, your code won't be in here when you do `chdir()`. Your signal handler should probably set a flag and return. You should probably use `sigaction()` rather than `signal()`. If you send `SIGKILL`, the receiving process won't get a second chance to do anything. – Jonathan Leffler Oct 23 '15 at 02:22
  • @JonathanLeffler, Suggest put your comment into an answer, so OP can mark it as accepted – user3629249 Oct 23 '15 at 06:57

0 Answers0