Search code examples
cunixfork

CTRL-C wont kill program linux/C


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?


Solution

  • 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);
    }