0

我不明白为什么我的代码不起作用。

这是我的代码。我不知道为什么我得到一个错误段。有人可以向我解释原因吗?

#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>

int id_process;

void manager_signal () {
    kill (id_process, SIGKILL);
    kill (getppid(),SIGKILL);
}

int main () {
    id_process = fork ();
    if (id_process==-1) {
        perror("ERROR to create the fork");
    } else {
        if ( id_process != 0 ) {
            printf("Father´s ID is %d \n", getpid());   
            alarm(5);
            (void) signal (SIGALRM, manager_signal);
            sleep (20);
            printf ("Running to where the father can be\n");
            alarm (0);          
        } else {
            printf ("CHildren´s ID is %d \n", getpid ());
            for (;;) {
                printf ( "Children RUN FOREVER ^^");
                sleep (2);
            }
        }
    }
    return 0;
}
4

2 回答 2

2

您的问题有点难以理解,因为您并没有真正解释错误是什么,但我确实有一个问题,我确信这将是相关的。

为什么“父亲”进程杀死了它的孩子和它的父母?它不应该杀死它的孩子和自己(id_processgetpid()不是getppid()哪个是父PID)吗?

这似乎是问题所在。当我在 Cygwin 下运行它时,它会杀死我的外壳(真烦人)。如果我将其更改为kill (getpid(),SIGKILL);,它会在五秒钟后正常终止,并显示以下输出:

$ vi qq.cpp ; g++ -o qq qq.cpp ; ./qq.exe
Fathers ID is 6016
Childrens ID is 4512
Children RUN FOREVER ^^
Children RUN FOREVER ^^
Children RUN FOREVER ^^
Children RUN FOREVER ^^
Children RUN FOREVER ^^
Killed

这是与程序修改如下:

#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>

int id_process;

void manager_signal (int x) {
    kill (id_process, SIGKILL);
    kill (getpid(),SIGKILL);
}

int main () {
    id_process = fork ();
    if (id_process==-1) {
        perror("ERROR to create the fork");
    } else {
        if ( id_process != 0 ) {
            printf("Fathers ID is %d\n", getpid());
            alarm(5);
            (void) signal (SIGALRM, manager_signal);
            sleep (20);
            printf ("Running to where the father can be\n");
            alarm (0);
        } else {
            printf ("Childrens ID is %d\n", getpid ());
            for (;;) {
                printf ( "Children RUN FOREVER ^^\n");
                sleep (1);
            }
        }
    }
    return 0;
}
于 2009-04-21T05:12:47.400 回答
0

我不认为

    kill (id_process, SIGKILL);

也是必需的。您将在下一条指令中杀死相同的进程。

于 2010-02-09T07:32:44.870 回答