我对C很陌生,我正在尝试编写一个迷你程序,当我遇到一个SIGINT时,它应该停止子进程(作为运行exec的叉子)或跳回循环的开始(打印出currentdir/>并等待输入)。目前,为了处理SIGINT,我必须在^C之后点击enter,但理想情况下,我不应该这样做。任何对此问题的帮助都将不胜感激!
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] = '\0'; //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,直到按enter之后。有人知道怎么解决这个问题吗?使用setjmp/longjmp会有帮助吗?如果他们能解决这些问题,我将如何实现?
发布于 2022-04-05 20:31:57
我不确定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
}
}https://stackoverflow.com/questions/71757803
复制相似问题