一种处理信号的打包方式?

时间:2016-08-10 14:44:19

标签: c++ signals

我有一个解决动态系统的程序。脱掉它的骨头,它看起来像这样:

#include <various_things.h>

double f(double t, double x, double p, double dt);

class Simulator {
  Simulator();
  void solve();

  double solution;
  double time, timeMax, timeStep;
  double parameter;
};

void Simulator::solve()
{
  while (time < timeMax)
  {
    solution = f(time, solution, parameter, timeStep);
    time += timeStep;
    printf("%f %f\n", time, solution);
  }
}

int main(int argc, char* argv)
{
  Simulator* sim = new Simulator(vp);
  if (argc <= 2) exit(-1);
  sim->time = 0;
  sim->solution = atof(argv[1]); // initial condition
  sim->parameter = atof(argv[2]); // 'parameters'
  /* ... */
  sim->solve();
}

首先通过参数指定初始条件和参数。然后Simulator::solve()执行一个更新解决方案的循环。

我想让它更具交互性,例如,可以传递SIGINT信号并指定新参数。所以,基于我能找到的信号处理教程,我尝试过这样的事情:

#include <signal.h>

static void handler(int signum, siginfo_t *siginfo, ucontext_t *context)
{
  /* What does context do? */
  printf("What should the new parameter value be? [%f]", sim->parameter);
  char buffer[1024];
  gets(buffer);
  if (strcmp(buffer, "\n") != 0)
    sim->parameter = atof(buffer);
  sim->solve();
}

/* This is now declared in the global scope. */
Simulator* sim;

int main(int argc, char* argv)
{
  /* I don't really understand how this bit works. */
  struct sigaction act;
  memset(&act, '\0', sizeof(act));
  act.sa_sigaction = &handler;
  act.sa_flags = SA_SIGINFO; // what?

  if (sigaction(SIGINT, &act, NULL) < 0)
  {
    /* Under what circumstances would this happen? */
    fprintf(stderr, "Could not handle signal.\n");
    perror("sigaction");
    return 1;
  }

  sim = new Simulator;
  if (argc <= 2) exit(-1);
  sim->time = 0;
  sim->solution = atof(argv[1]);
  sim->parameter = atof(argv[2]);
  /* ... */
  sim->solve();
 }

我认为此代码有效。但我有一些担忧:

  • 我担心在全球范围内宣布sim,但我不知道如何让handler()了解它。
  • 假设我想在另一个程序中使用Simulator。目前,信号处理在main()完成;是否可以使其成为Simulator的固有内容(以便使用Simulator的任何程序都能捕获信号)?

0 个答案:

没有答案