【问题标题】:How to receive the signal from child如何接收孩子的信号
【发布时间】:2015-05-24 16:13:50
【问题描述】:

编写一个使用fork()创建子进程的程序。子进程打印其父进程的名称、父 ID 和自己的 ID,而父进程等待来自子进程的信号。父母在孩子终止后 10 秒设置警报。

下面的代码没有收到孩子的报警信号,也没有进入报警处理程序,即ding函数。

我该怎么办?

using namespace std;

static int alarm_fired = 0;

void ding(int sig)
{

sleep(10);

 cout<<"Alarm\n";


}

int main()
{

int cpid,i,ppid;

int status = 0;

cpid=fork();

switch(cpid)

{

case -1:

        cout<<"error";

break;

case 0:

        cout<<"Child Block"<<endl;

        cout<<"Parent\n"<<"ParentID: "<<getppid()<<"\nChildID: "<<getpid();

        kill(getppid(), SIGALRM);

default:
        cout<<"Parent Waiting"<<endl;

        wait(&status);

        cout<<"Parent Waiting is Finished"<<endl; 

        signal(SIGALRM, ding);        
}
}

【问题讨论】:

    标签: c++ operating-system signals signal-handling


    【解决方案1】:

    您需要在孩子发送 SIGALARM 之前设置父信号处理程序“signal(SIGALRM, ding)”。在您的情况下,您可以在 fork() 上方移动“signal(SIGALRM, ding)”一行。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      相关资源
      最近更新 更多