【发布时间】:2018-05-25 14:28:06
【问题描述】:
以下代码出现错误。 它只执行与奇数相关的处理程序(以防父生成一个介于 1 和 10 之间的奇数随机数),而偶数的处理程序始终是“静音”的。 有人可以帮帮我吗?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <signal.h>
#include <math.h>
pid_t pid1,pid2;
int r, ric1, ric2;
int fd[4]; //per 2 processi figli
void handler_one(){
read(fd[0], &ric1, sizeof(int));
printf("Im the first child process...the even received numebr is...%d\n", ric1);
sleep(1);
}
void handler_two(){
read(fd[2], &ric2, sizeof(int));
printf("I'm the second child process...the odd receiver number is...%d\n", ric2);
sleep(1);
}
void main(){
pipe(fd);
pipe(fd+2);
pid1=fork();
if(pid1)
pid2=fork();
while(1){
if(pid1<0 || pid2<0){
perror("AN ERROR OCCURRED!!!!!!!\n");
exit(1);
}
else if(!pid1 && pid2){ //child #1
signal(SIGUSR1, handler_one);
}
else if(pid1 && !pid2){ //child #2
signal(SIGUSR2, handler_two);
}
else{ //padre
printf("I'm the parent and I'm gonna send a random number\n");
r=rand()%10+1;
if(r%2==0){
write(fd[1], &r, sizeof(int));
kill(pid1, SIGUSR1);
}
else{
write(fd[3], &r, sizeof(int));
kill(pid2, SIGUSR2);
}
sleep(1);
}
}
}
【问题讨论】:
-
您永远不会为随机生成器播种。所以我猜它总是产生相同的数字。
-
在你的 while 循环之前,试试这个:
printf("I am PID %u. pid1 is %u, pid2 is %u\n", getpid(), pid1, pid2);然后检查你的 if/else if 逻辑。 -
@pilcrow 这可能是比我更好的答案,因为它实际上是在教导而不是仅仅提供解决方案。
-
1)
void handler_one(int signum){(两个相同)2)你不应该在信号处理程序中使用printf()3)int main(void)