问题
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