3

我需要你的帮助来完成我关于进程之间信号处理的练习。我认为这是一个微不足道的问题,但我无法在任何地方找到答案。我想在文件中从父级打印一些东西,从父级向子级发送信号,子级必须在文件中打印,然后从子级向父级发送信号。

我正在使用的代码是这样的:

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

#define WRITEF 123451  //Random number

FILE *infile;

void writef() {
    fprintf(infile, "Child Starting (%d)\n", getpid());
    printf("Child Starting (%d)\n", getpid());
}

int main() {
    pid_t pid;

    infile = fopen("pid_log.txt","w");
    pid = fork();
    signal(WRITEF, writef);
    if ( pid == 0 ) {
            pause();
            printf("enter child\n");
    }
    else {
            fprintf(infile, "Parent (%d)\n", getpid());
            printf("Parent (%d)\n", getpid());
            kill(pid, WRITEF);
            pause();
            wait((int*)1);
    }

    fclose(infile);
    return 1;
}
4

1 回答 1

1

问题解决了!!!关键是您必须在每次 pause() 之前注册信号(使用信号函数)。此外,您不能使用“用户制造”信号,在我的情况下,我使用了 SIGCONT。

这是我的程序的最终(几乎)版本:

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

FILE *infile;

void noth() {

}

void writec() {
    infile = fopen("pid_log.txt","a+");
    fprintf(infile, "Child (%d)\n", getpid());
    printf("Child (%d)\n", getpid());
    fclose(infile);
}

void writep() {
    infile = fopen("pid_log.txt","a+");
    fprintf(infile, "Parent (%d)\n", getpid());
    printf("Parent (%d)\n", getpid());
    fclose(infile);
}

main() {
    pid_t pid = fork();

    if ( pid == 0 ) {                                               //child process
            signal(SIGCONT,noth);                          //registering signal before pause()
            pause();
            infile = fopen("pid_log.txt","a+");
            printf("Child Starting (%d)\n",getpid());
            fprintf(infile,"Child Starting (%d)\n",getpid());
            fclose(infile);
            while (1) {
                    sleep(2);

                    kill(getppid(), SIGCONT);                       //sending singal to parent

                    signal(SIGCONT, writec);

                    pause();
            }
    }
    else {                                                          //parent process
            infile = fopen("pid_log.txt","a+");
            printf("Parent Starting (%d)\n",getpid());
            fprintf(infile,"Parent Starting (%d)\n",getpid());
            fclose(infile);
            kill(pid, SIGCONT);
            signal(SIGCONT, writep);
            pause();
            while (1) {
                    sleep(2);

                    kill(pid, SIGCONT);

                    signal(SIGCONT, writep);

                    pause();
            }
    }
    return 1;
}
于 2012-10-18T06:40:30.300 回答