发送某些信号后如何停止进程关闭?

时间:2018-11-22 15:26:42

标签: c unix signals fork kill

我需要创建一个程序,该程序将创建将处理进程的子进程。在调用SIGXCPU的情况下,子进程应关闭,但是在收到其他信号时,进程不应关闭,而是显示信息。如何更改signals_handler函数以停止关闭进程?

我从第二个终端窗口呼叫信号。

void signals_handler(int signal) {
   psignal(signal,"\nRecived signal");
   printf("Signal number is: %d\n", signal);
   return;
}

void sig_XCPU(int signal() {
   signal(XCPU, sig_XCPU);
}

...

int main(void)
{

   if(fork() == 0) {
   print("PID: %d", getpid();
   signal(SIGXCPU, sig_xcpu)
   for(int = 1; i < 65; i++) {
       if(i != 24) //SIGXCPU number
       signal(i, signals_handler);
   }
   sleep(100);
   return 0;
   }
}

return 0;
}

1 个答案:

答案 0 :(得分:0)

您可以这样测试:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void signal_handle(int sig) {
  switch (sig) {
  case SIGXCPU: {
    char st[] = "child recesive SIGXCPU, quit\n";
    write(STDOUT_FILENO, st, sizeof(st));
    exit(EXIT_SUCCESS);
    break;
  }
  case SIGINT: {
    char st[] = "child recesive SIGINT\n";
    write(STDOUT_FILENO, st, sizeof(st));
    break;
  }
  default: break;
  }
 return;
}

void set_signal() {
  signal(SIGXCPU, signal_handle);
  signal(SIGINT,  signal_handle);
}

int main() {
  pid_t pid = fork(); 
  if (pid == 0) { // child
    set_signal();
    char st[] = "child set signal\n";
    write(STDOUT_FILENO, st, sizeof(st));
    for (;;)
      ;
  }
  // parent
  sleep(3); // wait child set_signal
  // test SIGINT
  {
    char st[] = "parent send SIGINT\n";
    write(STDOUT_FILENO, st, sizeof(st));
    kill(pid, SIGINT);
  }
  sleep(3);

  // test SIGXCPU 
  {
    char st[] = "parent send SIGXCPU\n";
    write(STDOUT_FILENO, st, sizeof(st));
    kill(pid, SIGXCPU);
  }
  wait(NULL);

  return 0;
}