我需要你帮助我完成一个关于进程间信号处理的练习。我认为这是一个微不足道的问题,但我无法在任何地方找到答案。我想在文件中打印来自父项的内容,从父项向孩子发送信号,孩子必须在文件中打印,然后从孩子发送信号给父母。
我正在使用的代码是:
#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;
}
答案 0 :(得分:1)
问题解决了! 关键是你必须在每次暂停()之前注册信号(使用信号功能)。此外,您不能使用“用户自制”信号,在我的情况下,我使用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;
}