c/c++语言开发共享在虚拟shell中处理CTRL-C

我正在编写一个虚拟shell,当用户输入ctrl-C时它不应该终止,但是应该只生成一个新的提示行。 目前,当我输入ctrl-C时,我的shell不会终止,但它仍然不会打印新的提示行。 你知道为什么会这样,我怎么解决这个问题?

我的代码如下:

#include  #include  #include  #include  #include  #include  #include  #define BUFFER_SIZE 1<<16 #define ARRAY_SIZE 1<= &bufCmdArgs[cmdArgsSize])) break; } for (p=n=0; bufCmdArgs[n]!=NULL; n++){ if(strlen(bufCmdArgs[n])>0) cmdArgs[p++]=bufCmdArgs[n]; } *nargs=p; cmdArgs[p]=NULL; } void INThandler(int sig) { printf("n> "); signal(sig, SIG_IGN); } int main(void) { char buffer[BUFFER_SIZE]; char *args[ARRAY_SIZE]; int retStatus; size_t nargs; pid_t pid; printf("$dummyshelln"); signal(SIGINT, INThandler); while(1){ printf("> "); fgets(buffer, BUFFER_SIZE, stdin); parseCmdArgs(buffer, args, ARRAY_SIZE, &nargs); if (nargs==0) continue; if (!strcmp(args[0], "help")) { printf("cat cd (absolute path references onlyn"); printf("exitn"); printf("help historyn"); printf("jobs killn"); printf("ls moren"); printf("ps pwdn"); continue; } if (!strcmp(args[0], "exit" )) exit(0); pid = fork(); if (pid){ wait(&retStatus); } else { if( execvp(args[0], args)) { fprintf(stderr, "%sn", strerror(errno)); exit(127); } } /* pid = fork(); if (pid == 0) setpgrp(); else if (pid) pid = wait(&retStatus); else { if (execvp(args[0], args)){ fprintf(stderr, "%sn", strerror(errno)); exit(127); } }*/ } return 0; } 

    但是我会通过fflush()传递什么?

    这将是

      fflush(stdout); 

    – 但由于fgets(buffer, BUFFER_SIZE, stdin)

    默认情况下,引用终端设备的输出流始终是行缓冲的; 每当读取引用终端设备的输入流时,就会自动写入对这些流的待处理输出。

    (见man stdio 。)

    我假设您希望中断处理程序跳转到main函数中的while循环,而不是打印">"

    你可以使用sigsetjmpsiglongjmp 。 你可能想以[1]为例。

     #include  #include  #include  jmp_buf JumpBuffer; void INThandler(int); void main(void) { signal(SIGINT, INThandler); while (1) { if (setjmp(JumpBuffer) == 0) { printf(">"); /*...*/ } } } void INThandler(int sig) { signal(sig, SIG_IGN); signal(SIGINT, INThandler); longjmp(JumpBuffer, 1); } 

    这改编自[2]。 如果使用sigaction()sigprocmask()sigsuspend() ,则需要分别使用siglongjmpsigsetjmp函数[3]。

    资料来源

      以上就是c/c++开发分享在虚拟shell中处理CTRL-C相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519148.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐