Stopping getline in C

五迷三道 提交于 2019-12-22 12:53:21

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/32747675/stopping-getline-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!