c - 在子进程中使用kill捕获信号?

标签 c signals shared-memory

在 Linux 上工作,我想捕获在子进程中使用 kill 发送的信号,然后打印循环,但我不知道如何操作。

我似乎无法获取捕获信号的代码。

这是迄今为止我的代码:

#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);  
 }
}

最佳答案

程序中的 pause() 本身不会捕获信号,它只是休眠直到信号被传递,但如果没有捕获该信号(使用 sigaction()signal(),正如 Jonathan Leffler 所写),它会终止该进程。所以,你必须添加e。 G。 signal(SIGUSR1, catch);pause();

之前
void catch(int signum) { }

main()之前。

关于c - 在子进程中使用kill捕获信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20737884/

相关文章:

c - C 代码的缓冲区溢出错误

linux - UDP 套接字上的接收通知

c - 如何向套接字发送信号?

Linux:信号源

linux - mmap 返回带有 shm_open 文件对象的 ENOMEM

c - 将数组附加到共享内存

c - 删除节点函数错误

c - 将元素添加到包含自定义数据类型的简单链接列表

c - 从列表中删除节点时出现段错误 (C)

c - 在 C 中运行时与应用程序交互