【问题标题】:C: Signal sending to children causes infinity loopC:向孩子发送信号导致无限循环
【发布时间】:2014-03-08 13:30:03
【问题描述】:

我的代码有以下问题。当子进程收到 SIGHUP 时,它(子进程)应该从 0 开始计数(工作正常),但是当父进程收到信号 hup 时,它应该让所有子进程再次从 0 开始计数,但是当发送信号时,会发生类似无限循环和 on_hup 函数for parent 一直被调用并且不会停止:(提前致谢。

#include <signal.h>
#include <stdio.h>
#include <wait.h>
#include <unistd.h>
#include <sys/types.h>
//#include "err.h"
#define NR_PROC 3

pid_t pid;
int a;
int pids[3];

void on_hup(int sig){    
    int i;
    if(pid!=0)           
        kill(0,SIGHUP);
    else    
        a=0;
}

void pierwsze(){
    for (;a<10000;a++){
        printf("%d: %d PID: %d \n",getpid(),a,pid);
    fflush(stdout);
    sleep(2);
} 

}

struct sigaction init(){
    struct sigaction sa;
    sigset_t block_mask;
    sigemptyset (&block_mask);
    sa.sa_mask = block_mask;
    sa.sa_flags=0;
    sa.sa_handler=on_hup;
    return sa;
}

int main(){
int i;
a=0;
struct sigaction setup_action = init();
sigaction(SIGHUP,&setup_action,0);

for(i=0;i<NR_PROC;i++){
    switch(pid = fork()){
      case -1:
        fprintf(stderr,"Error w fork \n");
      case 0:
        pids[i]=getpid();
        pierwsze();
        return 0;
      default:
        printf("I am parent My PID = %d\n",getpid());
        printf("fork = %d\n",pid);
    }
}
while(1){}
wait(0);
return 0;
}

【问题讨论】:

  • 我认为您的意图是让pids 包含所有子进程的进程ID,但不同进程之间不共享变量,因此当子进程设置pids[i]=getpid() 时,父进程的pids 数组不会改变。
  • 操作我的错误,但仍然将 pids[i] 更改为 0,并且仍然无法正常工作:(

标签: c process signals fork posix


【解决方案1】:

数组pids不能在父子之间共享。

因此,您可以从父上下文中插入 pid,而不是尝试将 pid 从子上下文中放入数组中:

代码如下所示:

case 0:
    pierwsze();
    return 0;
default:
    pids[i] = pid;
    printf("I am parent My PID = %d\n",getpid());
    printf("fork = %d\n",pid);

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 2015-09-27
    • 2021-01-03
    • 2011-07-13
    • 2015-12-27
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多