gpt4 book ai didi

捕获 SIGINT 信号以终止自定义 shell

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:05 31 4
gpt4 key购买 nike

希望你能帮我解决这个问题。

对于学校,我必须将 Ctrl+C 转换为不关闭 shell 的命令,但他通过 printf() 提醒我必须键入 exit关闭外壳。我什至不知道从哪里开始。

非常感谢。

最佳答案

这是使用 sigaction 处理 SIGINT 的简单实现这将适用于 posix 系统。为简洁起见,省略了错误检查。链接的手册应该解释sigaction

基本上,程序循环执行无限循环并在用户键入退出时中断。使用 write 因为您不能在信号处理程序中使用 printf。参见 signal manual获取可在信号处理程序中安全使用的函数列表。

#include<stdio.h>
#include<signal.h>
#include<string.h>
#include<stdlib.h>

char s[]="Type 'exit' to terminate\n";

void int_handler (int signum)
{
write(fileno(stdin), s, sizeof s - 1);
}

int main (void)
{
char str[256];
struct sigaction sh;

sh.sa_handler = int_handler;
sigemptyset (&sh.sa_mask);
sh.sa_flags = 0;
sigaction (SIGINT, &sh, NULL);
printf("%s", s);

while(1) {
fgets(str, sizeof str, stdin);
char *p = strchr(str, '\n');
if(p) *p = 0;
if(!strcmp(str, "exit")) {
printf("Exiting on request...");
break;
}
}
return 0;
}

关于捕获 SIGINT 信号以终止自定义 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31075177/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com