准确处理来自父进程的SIGUSR1类型的所有信号。 C

问题描述 投票:0回答:1

我想编写一个使用fork()函数创建N个子节点的程序。每个孩子将等待0到3秒,然后它会发送它的父母一个信号SIGUSR1。父处理所有这些信号。

问题是我的程序并不总是处理来自它的孩子的所有信号。怎么修呢?

第二个问题:我知道我不应该在处理程序中使用printf,因为可能会发生一些不好的事情。我怎样才能替换这条指令?

main.c中

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

void error(char *s){
    printf("%s\n",s);
    perror("Program execution failed.");
    exit(EXIT_FAILURE);
}

volatile int N=8; //final number of children
volatile int k=0; //number of received SIGUSR1 signals

void childRequestHandler(int signo, siginfo_t* info, void* context){
    k++;
    printf("%d,Father received request from child: %d\n",k,info->si_pid);

}

int main() {
    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO;
    act.sa_sigaction = childRequestHandler;
    if(sigaction(SIGUSR1,&act,NULL) == -1) printf("ERROR OCCURED");

    for(int i=0;i<N;i++){
        pid_t pid = fork();
        if(pid == 0) {
            execl("./child", "./child", NULL);
            error("Fork error happened\n");
        }
    }

    while (1){
        sleep(1);
    }

}

child.c

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>



int main() {
    time_t t;
    srand((unsigned int) getpid()+ time(NULL));


    int length_of_sleeping = rand() % 4 ;
    printf("I live: %d, sleeps %ds \n",getpid(),length_of_sleeping);
    sleep(length_of_sleeping);
    kill(getppid(),SIGUSR1);

    while(1){

    }

}

输出:

I live: 4195, sleeps 3s 
I live: 4196, sleeps 3s 
I live: 4197, sleeps 1s 
I live: 4202, sleeps 3s 
I live: 4198, sleeps 0s 
I live: 4201, sleeps 2s 
I live: 4199, sleeps 0s 
I live: 4200, sleeps 3s 
1,Father received request from child: 4198
2,Father received request from child: 4197
3,Father received request from child: 4201
4,Father received request from child: 4195
c printf fork execl
1个回答
1
投票

当信号处理程序执行时,信号被阻止。在此期间收到的所有SIGUSR1信号都不会被注意到。

您可以在建立信号时使用SA_NODEFER标志,有关标志的信息,请参阅the sigaction manual page

但是,如果你使用SA_NODEFER,请不要使用printf!它不是异步信号安全功能。参见例如this manual page about signal safety了解更多信息。


来自the POSIX sigaction reference

当信号被sigaction()安装的信号捕获功能捕获时,计算并安装一个新的信号掩码,用于信号捕获功能的持续时间....这个掩码是通过获取当前信号掩码和sa_mask的值为传递的信号,除非设置SA_NODEFERSA_RESETHAND,然后包括传递的信号。如果用户的信号处理程序正常返回,则恢复原始信号掩码。

[强调我的]

© www.soinside.com 2019 - 2024. All rights reserved.