C未正确接收实时信号

时间:2017-04-05 20:41:05

标签: c signals

我写了一些代码,它应该如下工作:我正在创建一个子进程,然后向他发送N个实时信号(例如SIGRTMIN),然后发送给其他实时信号(例如SIGRTMAX)。子进程应该有合适的信号处理程序发送回SIGRTMIN信号,在SIGRTMAX之后,他应该结束。我的问题是,如果我发送给孩子10个信号,有一次我在父10个信号中接收,一次0和一次只有1个信号。我希望收到的信号总是和我发送的信号一样多。有人可以建议吗? 父:

#define _BSD_SOURCE

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

int requests, child_pid, income_signal_counter = 0;
struct sigaction new;
union sigval sigval_tmp;


void generateChild(){
    int pid = fork();
    if (pid == 0){
        if(execvp("./child", NULL) == -1){
            printf("Sth goes wrong\n");
            exit(1);
        }
        exit(0);
    }else if(pid > 0){
        usleep(100000);
        child_pid = pid;
    }
}      

void sendSignalsByKillWithRTSignals(){
    int signal_sent = 0;
    for(int i =0; i<requests; i++){
        if(kill(child_pid, SIGRTMIN)== 0){
            signal_sent ++;
        }
    }
    printf("(parent)Wyslanych sygnalow SIGRTMIN: %d\n", signal_sent);
    kill(child_pid, SIGRTMAX);
}
  void RTMinSignalHandler(){
    income_signal_counter++;
   // printf("(parent)Liczba otrzymanych SIGRTMIN: %d/%d\n", income_signal_counter, requests);
}


int main(int argc, char *argv[]){
    requests = atoi(argv[1]);
    int  func_type = atoi(argv[2]);

    generateChild();
    struct sigaction new;
    new.sa_handler = &RTMinSignalHandler;
    new.sa_flags = 0;
    sigaction(SIGRTMIN, &new, NULL);


    sendSignalsByKillWithRTSignals();

    int wstatus;
    wait(&wstatus);
    if(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0){
        printf("Proces potomny zdechl\n");
        exit(2);
    }

    printf("(parent)Signal SIGRTMIN received: %d/%d\n", income_signal_counter, requests);
    return 0;
}

子:

#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

volatile int parent_id;

void signalHandler(int signal){
    kill(parent_id, signal);
}

void exitSignalHandler(int signal){
    _exit(0); 
}

int main(int argc, char *argv[]){
    parent_id = getppid();
    struct sigaction new;

    new.sa_handler = &signalHandler;
    new.sa_flags = 0;
    sigaction(SIGRTMIN, &new, NULL);

    new.sa_handler = &exitSignalHandler;
    new.sa_flags = 0;
    sigaction(SIGRTMAX, &new, NULL);

    while(1){
    }
    return 0;
}

0 个答案:

没有答案