简体   繁体   English

在子进程中使用kill的陷阱信号?

[英]Trap signal using kill in child process?

Working on Linux, I want to catch the signal I have sent using kill in the child process and then print the loop but I don't know how. 在Linux上工作时,我想捕获在子进程中使用kill发出的信号,然后打印循环,但我不知道如何。

I can't seem to get my code that catches the signal. 我似乎无法获得捕捉信号的代码。

Here is my code so far: 到目前为止,这是我的代码:

#include <stdio.h>
#include <signal.h>
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/shm.h> 

int SHMSIZE = 9;
int alarmFlag = 0;

void main()
{
 int shmid; 
 int *shm; 
 pid_t pid = fork();

 if(pid == 0) {
  pause();
  shmid = shmget(4000, SHMSIZE, 0);
  shm = shmat(shmid,0,0);

  int i;
  for(i=0;i<SHMSIZE;i++)
   printf("<%d , ",shm[i]);
 }
 else
 {
   int *n;
   shmid = shmget(4000,SHMSIZE,0666 | IPC_CREAT);
   shm = shmat(shmid,0,0);
   n = shm;  

   int i;
   for(i=0;i<SHMSIZE;i++)
    n[i] = i;

   int result = kill(pid, SIGUSR1); 
   wait(NULL);  
 }
}

The pause() in your program on its own doesn't catch a signal, it just sleeps until a signal is delivered, but if that signal isn't caught (using sigaction() or signal() , as Jonathan Leffler wrote), it terminates the process. 程序中的pause()本身不会捕获信号,它会一直休眠直到传递信号为止,但是如果未捕获到该信号(使用sigaction()signal() ,如Jonathan Leffler所写),它终止了该过程。 So, you have to add eg signal(SIGUSR1, catch); 因此,您必须添加例如signal(SIGUSR1, catch); before pause(); pause();之前pause(); and

void catch(int signum) { }

before main() . main()之前。

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

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