簡體   English   中英

捕獲SIGINT信號以終止自定義shell

[英]Catching SIGINT signal to terminate a custom shell

希望你能幫我解決這個問題。

對於學校我必須將Ctrl + C轉換為不關閉shell的命令,但他通過printf()提醒我必須鍵入exit才能關閉shell。 我甚至不知道從哪里開始。

非常感謝。

這是一個使用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;
}

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 ;
  }

當你在談論從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解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM