【问题标题】:Count number of times signal is sent to child by parent计数父母向孩子发送信号的次数
【发布时间】:2015-03-10 06:32:08
【问题描述】:

让程序计算向子进程发送信号的次数时遇到了一点问题。显示错误的值。 父级应通过管道将数组的每个元素发送给子级,然后子级应读取并显示发送的内容。 count 保存发送给孩子的信号数量。 请问有什么帮助吗?

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>

int count = 0;//number of SIGUSR1 signal sent to child by parent

void sigHandler(int signum){
    signal(SIGUSR1, sigHandler);
    if (signum == SIGINT){
        printf("SINGINT Received\n");
        count++;
    }   
}

int main(void){
    int pid, fd[2], ato, i;
    pipe(fd);
    pid = fork();
    int x[] = {1, 2, 3, 4, 5, 6, 7};
    char bufP[3], bufC[3];
    signal(SIGINT, sigHandler);
    if (pid == 0){
        //child         
        printf("I am Child\n");     
        close(fd[1]);
        read(fd[0], bufC, sizeof(bufC));
        close(fd[0]);
        ato = atoi(bufC);
        printf("Child read: %d\n", ato);
        sleep(2);
    }else{
        //parent
        printf("I am Parent\n");            
        for (i=0; i<7; i++){
            close(fd[0]);
            sprintf(bufP, "%d", x[i]); 
            write(fd[1], bufP, sizeof(bufP));                
            close(fd[1]);               
            sleep(1);
            kill(pid, SIGINT);  //sending signal to child               
        }                       
    }       
    printf("Count: %d\n", count); //number of times signal was sent     
}

谢谢

【问题讨论】:

  • 第一个avoid using printf in a signal handler,第二个是因为信号处理程序可以是异步的,所以count类型应该是sig_atomic_t - 也读What happens during this signal handling program?
  • 也看这个Use reentrant functions for safer signal handling,看完这个博客你就能正确的写出你的程序了。
  • 为什么要关闭fd[0]fd[1] 七次?不仅如此,您还尝试在关闭fd[1] 后写信给它。另外,您希望获得多少信号?您的孩子没有循环,因此它将在 2 秒后打印。在那段时间你只会收到大约 2 个信号。
  • 您的程序似乎在做两件不同的事情:通过管道进行进程间通信和信号计数。尝试将其缩小到一件事以简化代码,因为它会让您更容易发现问题。以下是一些随机观察: 1. 您计算的是 SIGINT,而不是 SIGUSR1。为什么您的信号处理程序要安装另一个信号处理程序? 2. 您正在为父母和孩子安装 SIGINT 处理程序。这是故意的吗? 3. 就像 JS1 说的那样,你不能在下一次迭代中 close() 然后 read() -- 它会被关闭。

标签: c signals


【解决方案1】:

对信号进行计数是不安全的。多个终止信号可以合并为接收器上的开启信号接收。将终止/信号视为硬件中断信号。仅将它们用于轻推,但不要依赖于每一个都不会与具有相同信号值的其他实例合并。

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多