简体   繁体   English

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

[英]Catching SIGINT signal to terminate a custom shell

Hope you can help me to resolve this problem. 希望你能帮我解决这个问题。

For school I have to transform Ctrl+C to a command which doesn't shut down the shell, but he reminds through printf() that I must type exit to close the shell. 对于学校我必须将Ctrl + C转换为不关闭shell的命令,但他通过printf()提醒我必须键入exit才能关闭shell。 I don't even know where to start. 我甚至不知道从哪里开始。

Thank a lot. 非常感谢。

Here's a trivial implementation of handling SIGINT using sigaction which will work on posix systems. 这是一个使用sigaction处理SIGINT的简单实现,它可以在posix系统上运行。 Left out error checking for brevity. 遗漏错误检查以简洁。 The linked manual should explain about sigaction . 链接手册应该解释sigaction

Basically the program loops through an infinite loop and break if user types exit. 基本上程序循环通过无限循环并在用户类型退出时中断。 Using write as you can't use printf in signal handler. 使用write因为你不能在信号处理程序中使用printf。 See signal manual for a list of functions that can be used safely in a signal handler. 有关可在信号处理程序中安全使用的功能列表,请参阅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;
}

Ctrl+C sends an interrupt signal (SIGINT) to the running process.You can use signal() to catch SIGINT like this: 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 ;
  }

As you're talking about doing it from the shell, you probably want: 当你在谈论从shell中做这件事时,你可能想要:

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

This specifies a command to execute when the listed signal is trapped (the trap command can also trap other signals; SIGINT is the one generated by Ctrl-C ). 这指定了捕获列出信号时要执行的命令( trap命令也可以捕获其他信号; SIGINT是Ctrl-C生成的信号)。 The \\' protects the quote from being interpreted by the shell. \\'保护引用不被shell解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM