该程序的目标是 fork 并使 child 入睡,而父级循环无限地等待中断。当我按下^ C时,它将调用void parent函数。这部分有效,但是来自kill ( pid, SIGALRM )的消息不起作用。我检查了pid是该 child 的正确进程ID。

我搜索了一段时间,但没有发现我做错了什么。从子进程到父进程之前,我都使用了kill ( pid, SIGALRM ),但是我不知道为什么这不起作用。

#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int pid;

void parent ( int sig )
{
        kill ( pid, SIGALRM );
        cout << "I'm a parent " << getpid() << " My child is " << pid << endl;
}

void child ( int sig )
{
        cout << "I am " << getpid() << "my parent is " << getppid()<< endl;
        cout << "Use ctrl+backslash to actually end the program" << endl;
}
int main()
{
        pid = fork();
        if(pid == 0)
        { //Child process
                cout << "Child pid = " << getpid() << " Waiting for interrupt." << endl;
                (void) signal ( SIGALRM, child );
                pause();
        }
        else if(pid > 0)
        { //Parent
                sleep(2);
                cout << "child pid = " << pid << endl;
                struct sigaction act;
                act.sa_handler = parent;
                sigemptyset ( &act.sa_mask);
                sigaction (SIGINT, &act, 0);
                while(1)
                {
                        sleep ( 1 );
                }
        }
        return 0;
}

最佳答案

好的,所以我找出了问题所在。
当我按^ C时,它将捕获主进程中的中断,但杀死子进程。当我从程序内部运行system("ps")时,它表明子a.out进程已失效。
为了解决这个问题,我在 child 的过程中添加了以下内容:

struct sigaction act;
act.sa_handler = CHILD_PRESERVER;
sigemptyset ( &act.sa_mask);
sigaction (SIGINT, &act, 0);
CHILD PRESERVER是一个伪函数,除了保持 Activity 之外什么也没做。

它没有看到此解决方案非常优雅,因此,如果有人有更正确的方法,请发布它。

关于c++ - C++ Process fork和sigalarm,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9289234/

10-09 20:36
查看更多