0
char *args = "echo hey";

pid_t pid = fork();
if(pid == 0) {
    while(1) {
        pid2 = fork();
        wait(NULL);
    }
}

If I have a program as such

$ gcc -Wall above.c
$ ./a.out
hey
hey
hey
hey
hey
hey
C^hey
hey

Ctrl+C isn't killing the program, how do I make Ctrl+C stop the child from running?

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
  • 4
    Possible duplicate of [Cannot kill Python script with Ctrl-C](https://stackoverflow.com/questions/11815947/cannot-kill-python-script-with-ctrl-c) – Michael Mar 20 '18 at 19:56

1 Answers1

4

The parent process that started code probably exited while the first child was inside of the infinite loop, so keyboard input is no longer received by the child.

You need to keep the parent process up by having it wait for the first child:

if(pid == 0) {
    while(1) {
        pid2 = fork();
        if(pid2 == 0) {
            execlp("sh", "sh", "-c",args, (char *)NULL);
            perror("sh");
            return(1);
        }
        wait(NULL);
    }
} else {
    wait(NULL);
}
dbush
  • 205,898
  • 23
  • 218
  • 273