如何使子进程等待它的兄弟?

时间:2012-06-30 06:16:42

标签: c unix ipc process

我是按照[Mat] [1]的建议使用IPC来解决它,但我仍然无法做到  它和样品运动的方式,而不是作业!但我的考试就这样了  请帮帮我...... :)  有人在这里指出我做错了什么.Kid2没有发送或者父母没有收到来自孩子2的任何信号。

感谢名单。

#include<stdio.h>  
#include<sys/wait.h>  
#include<wait.h>  
#include<signal.h>  

void my_handler_for_kid2(int sig_num){  
  printf("KID2:Recieved SIGUSR1 from KID1\n");  
}  
void my_handler_for_parent(int sig_num){  
  printf("PARENT:Recieved SIGUSR2 from KID2\n");  
}  

int main(){  
  int status;  
 pid_t kid1,kid2;  

  void my_handler_for_kid2(int sig_num);  
  void my_handler_for_parent(int sig_num);  
  signal(SIGUSR1,my_handler_for_kid2);
  signal(SIGUSR2,my_handler_for_parent);
  kid1=fork();  
  if(kid1 < 0){  
    printf("Fork not successfull\n");  
  }  
  else if(kid1 == 0){  
    printf("I am KID1[%ld] and I am going to sleep\n",(long) getpid());  
    sleep(5);  
    printf("Just woke up!\n");  
    kill(kid2,SIGUSR1);  
      }  
  else{  
    kid2=fork();  
    if(kid2 < 0){ 
      printf("Fork not successfull\n");  
    }  
    else if(kid2 == 0){  
      printf("I am KID2[%ld] and I am going to wait for KID1 to wakeup\n",(long)       getpid());  
      pause(); 
      //signal(SIGUSR1,my_handler_for_kid2);  
      kill(getppid(),SIGUSR2);  
    }  
    else{  
      printf("Father[%ld] here and going to wait for both kids to respond to me\n",    (long) getpid());  
      pause();
      //signal(SIGUSR2,my_handler_for_parent);  
      waitpid(kid1,&status,NULL);  
      waitpid(kid2,&status,NULL);  
    }  
 }  
} 

rizwan@riz-pc:~/Documents$ ./a.out
I am KID1[2278] and I am going to sleep
 Father[2277] here and going to wait for both kids to respond to me
 I am KID2[2279] and I am going to wait for KID1 to wakeup
 Just woke up!
KID2:Recieved SIGUSR1 from KID1
^C
rizwan@riz-pc:~/Documents$ 








  [1]: http://stackoverflow.com/users/635608/mat  

3 个答案:

答案 0 :(得分:6)

来自POSIX

  

wait()和waitpid()函数应获取与其中一个调用者的子进程有关的状态信息。

您不能使用这些功能在兄弟姐妹之间进行同步,只能从等待其子女的父母一方进行同步 您需要使用一些“真实”同步原语来实现您所追求的目标(信号量或其他形式的IPC)。

答案 1 :(得分:1)

Mutex同步可以正常工作。

答案 2 :(得分:0)

为此,您应该使用条件变量。从网上学习任何教程。