Stopping getline in C

2019-05-26 22:41发布

Here I'm trying to get an user input with getline. Upon receiving an interrupt ^C I want it to signal getline to stop and resume with my program instead of terminating it.

I tried to write a newline to stdin but apparently that doesn't work.

fwrite("\n", 1, 1, stdin);

So what would be a way to achieve this?

标签: c signals stdin
1条回答
看我几分像从前
2楼-- · 2019-05-26 23:04

Assuming your code resembles this:

int main(int argc, char **argv) {
    //Code here (point A)
    getline(lineptr, size, fpt);
    //More code here (point B)
}

Include <signal.h> and bind SIGINT to a handler function f.

#include <signal.h>

//Declare handler for signals
void signal_handler(int signum);

int main(int argc, char **argv) {
    //Set SIGINT (ctrl-c) to call signal handler
    signal(SIGINT, signal_handler);

    //Code here (point A)
    getline(lineptr, size, fpt);
    //More code here (point B)
}

void signal_handler(int signum) {
    if(signum == SIGINT) {
        //Received SIGINT

    }
}

What I would do at this point is restructure the code so that any code after point B is in its own function, call it code_in_b(), and in the handler call code_in_b().

More information: Signals

查看更多
登录 后发表回答