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

时间:2015-06-26 13:59:10

标签: c signals system-calls

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

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

非常感谢。

3 个答案:

答案 0 :(得分:3)

这是一个使用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;
}

答案 1 :(得分:0)

Ctrl + C向正在运行的进程发送中断信号(SIGINT)。您可以使用signal()来捕获SIGINT,如下所示:

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

 void sigint_handler(int sig)
 {
   printf("Type exit to close the shell!\n");
 }


  int main()
  {
    signal(SIGINT, sigint_handler);

    /*Your code should replace the while loop.*/
    while(1)
    {
        printf("Running!\n");
        getchar();
    }

    return 0 ;
  }

答案 2 :(得分:0)

当你在谈论从shell做这件事时,你可能想要:

$ trap "echo Please type \'exit\' to close the shell." SIGINT
<Ctrl-C>
Please type 'exit' to close the shell.
$

指定捕获列出的信号时要执行的命令(trap命令也可以捕获其他信号; SIGINT是Ctrl-C生成的信号)。 \'保护引用不被shell解释。