简体   繁体   English

c SIGINT表现如何?

[英]c SIGINT acting up?

I'm experimenting with SIGINT. 我正在尝试SIGINT。 I basically want my program to start as soon as the user hits control-c. 我基本上希望我的程序在用户点击Control-c后立即启动。 When this happens, I'm going to then get the program to make a pipe. 发生这种情况时,我将获取程序以制作管道。

Now, I decided that when control-c is pressed in the signal handler it will call a function to create the pipe. 现在,我决定在信号处理程序中按Control-c时,它将调用一个函数来创建管道。 Yet this is messing up. 但这真是一团糟。 It's fine running a printf command but refuses to carry out the if statement until you press control-c again. 运行printf命令很好,但是拒绝执行if语句,直到再次按下Ctrl-c为止。 Anyone able to assist? 有人可以协助吗?

Realistically, I want to disable control-C after it has been pressed once. 实际上,我想在按下Control-C后禁用它。

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

void catchme(int signal);
void Setup();


int main()
{
  if (signal(SIGINT, catchme) == SIG_ERR)
  {
    write(2, "Error catching signal C\n", 26);
  } 

  printf("To begin, please press CTRL + C\n");
  for(;;);
  return 0;
}

void catchme(int signal)
{
  write(1, "\n Caught Signal from Control C\n", 33);
  Setup();
}

void Setup()
{
  int firstPipe[2];

  printf("Lets set up...\n");

  if (pipe(firstPipe) < 0)
  {
    printf("Error creating pipe 1\n");
    //abort program
  }
  else
  {
    printf("working so far");
  }
}

You should get a debugger working. 您应该使调试器正常工作。 It would provide you with the answer to your question within seconds, and it's essential for trying to track down these kinds of problems. 它会在几秒钟内为您提供问题的答案,这对于尝试查找此类问题至关重要。 What seems very mystifying and unclear, when you're trying to interpret the output, will seem very easy when you're stepping through it, and you can see everything. 当您尝试解释输出时,看起来非常神秘和不清楚的东西在逐步执行时似乎非常容易,并且您可以看到所有内容。

This will probably lead to pipe() not doing what you expect, you'll check errno, and presumably get a useful answer. 这可能会导致pipe()未按预期执行操作,您将检查errno,并可能获得有用的答案。

The commenter's advise about avoiding doing stuff in signal handlers is good, as it's not portable. 评论者关于避免在信号处理程序中执行操作的建议是好的,因为它不是可移植的。 However, most modern OSs are quite permissive, so I'm not sure if that's your problem in this case. 但是,大多数现代操作系统都相当宽松,因此,在这种情况下,我不确定这是否是您的问题。

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

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