C语言 SIGINT with getchar()



我是C语言的新手,正在尝试编写一个小单元程序,该程序应该在我运行SIGINT时立即停止子进程(作为运行exec的fork的结果(或跳回到循环的开始(打印出[currentdir/]>并等待输入(。目前,我必须在^C之后点击回车键才能处理SIGINT,但理想情况下,我不应该这样做。如果能在这个问题上提供任何帮助,我们将不胜感激!

volatile sig_atomic_t interrupted = 0; //interrupted is originally set to false.
void sig_handler(int sig)
{
interrupted = 1;
//printf("n");
}
int main_helper()
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sig_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGINT, &sa, NULL) == -1)
{
fprintf(stderr, "Error: Cannot register signal handler. %s.n", strerror(errno));
exit(1);
}

/* code to get current directory and print it in the format [dir/]> */
while (is_exit == 0) //because no booleans
{
/*
getting user input.
*/
input_str = malloc(sizeof(char)); //starting out w a str of length 1.
if (input_str == NULL)
{ //if the malloc fails for some reason.
fprintf(stderr, "Error: malloc() failed. %s.n", strerror(errno));
exit(1);
}
int c; //the character that we're at
int i = 0;
//read chars until null term or eof found
while ((c = getchar()) != 'n')
{
if (c == EOF)
{
fprintf(stderr, "Error: Failed to read from stdin. %s.n", strerror(errno));
exit(1);
}
input_str[i++] = c;
input_str = realloc(input_str, i + 1); //adding space for another
if (input_str == NULL)
{ //if it can't realloc for some reason.
fprintf(stderr, "Error: realloc() failed. %s.n", strerror(errno));
exit(1);
}
}
input_str[i] = ''; //adding null terminator at the end.

/*
dealing with the input using exec or built-in functions
*/
free(input_str); //free the input that we just realloced stuff for
interrupted = 0;
}
return EXIT_SUCCESS;
}

现在,我不完全确定为什么会发生这种情况,但如果我正确理解其他一些StackOverflow线程,getchar()函数可能会阻塞SIGINT,直到按下回车键。有人知道怎么解决这个问题吗?使用setjmp/longjmp有帮助吗?如果他们能解决这个问题,我该如何实施?

我不确定SIGINT,但您可以使用fread编写一个非阻塞的getchar

unsigned char buffer;
while (fread(&buffer, sizeof(buffer), 1, stdin) == 0) {
// Check signal in here

// If no character was read, check if it was due to EOF or an error
if (feof(stdin)) {
// We reached the end of the file
}
if (ferror(stdin)) {
// An error occurred when we tried to read from stdin
}
}

最新更新