2014-06-18 40 views
0

我必須同步2個進程與命名管道。父親必須打印n次「Ping」,然後將「C」發送給打印「Pong」的兒子。在拉斯「平」之後,父親發送「Q」,兒子打印最後一個「Pong」並離開終止。它正在工作,但有時最後的乒乓球沒有打印。namedpipe pingpong syncronizate processes

void pingpong(int n) 
{ 
    char buffer; 
    pid_t pid; 
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP; 
    int descEcriture, descLecture; 
    if (mkfifo(("père"), mode) < 0){ 
     perror("mkfifo"); 
    } 
    if (mkfifo(("fils"), mode) < 0){ 
     perror("mkfifo"); 
    } 
    if ((pid = fork()) < 0){ 
     perror("fork"); 
     exit(-1); 
    } 
    if(pid == 0){ 
     while(1){ 


      if((descEcriture = open("père", O_WRONLY)) < 0){ 
       perror("père Tube"); 
       exit(-1); 
      } 
      if(n == 0){ 
       write(descEcriture, "Q", 1); 
       break; 
      } 
      write(STDOUT_FILENO, "Ping", strlen("Ping")+1); 
      write(descEcriture, "C", 1); 
      close(descEcriture); 
      if((descLecture = open("fils", O_RDONLY))<0){ 
       perror("père Tube"); 
       exit(-1); 
      } 
      read(descLecture, &buffer, 1); 
      close(descLecture); 
      n--; 
     } 
     exit(0); 
    } 
    else 
    { 
     while(1){ 
      if((descLecture = open("père", O_RDONLY)) < 0){ 
       perror("pere Tube"); 
       exit(-1); 
      } 
      read(descLecture, &buffer, 1); 
      if (buffer == 'C') 
      { 
       write(STDOUT_FILENO, "Pong", strlen("Pong")+1); 
      } 
      if (buffer=='Q') 
      { 
       break; 
      } 
      if((descEcriture = open("fils", O_WRONLY)) < 0){ 
       perror("fils Tube"); 
       exit(-1); 
      } 
      write(descEcriture, "K", 1); 
     } 
     unlink("père"); unlink("fils"); 
     exit(0); 
    } 

} 

回答

0

沒有理由在循環的每次迭代中打開和關閉管道。嘗試在循環之前打開管道並關閉它們。

此外,由於您將strlen的返回值加1,因此您在字符串「ping」和「pong」後打印空字節。嘗試這樣的:

// Near top of program: 
#define PING "ping" 
#define PONG " : pong\n" 

// In pingpong function: 
     // In parent: 
     write(STDOUT_FILENO, PING, strlen(PING)); 
     // In child: 
     write(STDOUT_FILENO, PONG, strlen(PONG)); 

而你似乎有父母和孩子混在一起。如果pid爲0,那麼它是孩子,而不是父母。