捕获SIGINT信号终止定制外壳 [英] Catching SIGINT signal to terminate a custom shell

查看:143
本文介绍了捕获SIGINT信号终止定制外壳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hope you can help me to resolve this problem.

有关学校里,我不得不改变<大骨节病>按Ctrl + C 到不关机的外壳,但他通过提醒printf的命令()我必须键入exit关闭shell。我甚至不知道从哪里开始。

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. I don't even know where to start.

感谢了很多。

推荐答案

下面是一个简单的实现使用的 SIGINT http://man7.org /linux/man-pages/man2/sigaction.2.html相对=nofollow> 的sigaction 这将在POSIX系统工作。离开了错误检查简洁。链接的手册应约的sigaction 解释。

Here's a trivial implementation of handling SIGINT using sigaction which will work on posix systems. Left out error checking for brevity. The linked manual should explain about sigaction.

基本上程序遍历一个无限循环,如果用户键入退出突破。使用因为你不能使用信号处理程序的printf。请参见 信号手动 为可以安全地在信号处理程序使用的函数列表。

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. See signal manual for a list of functions that can be used safely in a signal handler.

#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信号终止定制外壳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆