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

エラーが何であるかを実際に説明していないため、質問を理解するのは少し難しいですが、関連があると確信している質問が1つあります。

「父」プロセスがその子とそのを殺すのはなぜですか? その子とそれ自体を殺すべきではありませんか(id_processそしてgetpid()どちらがgetppid()親PIDであるかではありません)?

それが問題のようです。Cygwinでそれを実行すると、シェルが強制終了されます(面倒です)。に変更するとkill (getpid(),SIGKILL);、5 秒後に問題なく終了し、次の出力が表示されます。

$ 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 に答える