2015-09-04 233 views
1

我正在写一个Unix程序,其中父进程分叉孩子p1.the父进程处理SIGUSR1。
子进程每1秒产生一个1到9之间的随机数并使用管道发送给父亲父接收该数字并将其打印到控制台。当父进程接收到SIGUSR1信号时,他开始只打印奇数并且当收到的号码是11时,他通过发送SIGTERM信号杀死孩子。父亲等待状态,然后终止孩子。孩子和父母之间的进程间通信C

#include<stdio.h> 
#include<unistd.h> 
#include<stdlib.h> 
#define READ_END 0 
#define WRITE_END 1 
volatile sig_atomic_t token; 
void handle_me(int signum) 
{ 
    token=0; 
} 
int main(int argc, char *argv[]){ 
     pid_t child1; 
     token=1; 
     int pipe1[2],status; 
     unsigned int bufChild1,bufChild2; 
     if (pipe(pipe1) == -1) 
     { 
      fprintf(stderr, "Pipe failed"); 
     } 
     child1 = fork(); 
     if (child1 < 0) 
     { 
      fprintf(stderr, "Fork Failed"); 
      return 0; 
     } 
     else if (child1 == 0) 
     { 
      printf(" child with pid %d\n", getpid()); 
      printf("The Parent pid is %d\n", getppid()); 
      while(1) 
      { 
        bufChild1 = (unsigned int)rand()%9 +1; 
        fprintf(stdout, "generated: %u\n", bufChild1); 
        close(pipe1[READ_END]); 
        write(pipe1[WRITE_END],&bufChild1,sizeof(bufChild1)); //write into the Parent 
        close(pipe1[WRITE_END]); 
      } 
     } 
     else 
     { 
      signal(SIGUSR1,handle_me); 
      printf(" Parent Process\n"); 
      while(!token) 
      { 
        close(pipe1[READ_END]); 
        read(pipe1[READ_END],&bufChild2,sizeof(bufChild2)); //write into the Parent 
        fprintf(stdout, "Received: %u\n", bufChild2); 
        close(pipe1[WRITE_END]); 
      } 
     } 
     wait(&status); 
     return 1; 
} 

我不知道如何实现这一条件时,父进程捕捉SIGUSR1信号,他开始只打印奇数当收到数是11,他通过发送SIGTERM信号杀死了孩子。

我使用了一个全局变量,如果SIGUSR1被父亲捕获,可以设置它。
如果有人能帮助我,我将非常感激。

回答

0

该程序包含一些错误。

  • 你忘了#include <signal.h>
  • 要使子进程每1秒钟完成一次工作,必须将sleep(1)放入子进程的while循环中。
  • 孩子一定不能close(pipe1[WRITE_END]);否则它不能写入父母。
  • 父母一定不能close(pipe1[READ_END]);否则它不能再读取孩子。

我不知道如何实现这一条件时,父进程捕捉 的SIGUSR1信号,他开始只打印奇数...

您已经实施清除变量token当信号被捕获,所以你可以改变父母的一部分到e。 G。

  close(pipe1[WRITE_END]); 
      while (read(pipe1[READ_END], &bufChild2, sizeof bufChild2) > 0) 
       if (token || bufChild2&1) 
        fprintf(stdout, "Received: %u\n", bufChild2); 

...当收到数是11,他通过发送 SIGTERM信号,杀死了孩子。

这将不会发生,因为程序生成“之间1〜9一个随机数”。

相关问题