2013-10-07 37 views
0

使用c中的管道創建一個程序,用於確定用戶輸入的整數是偶數還是奇數。此外,它應該 達到以下規格: 父進程應發送整數到分叉的子進程。 子進程應該接收發送的整數來確定他的類型(偶數或奇數)。 然後,結果應該返回到父進程,以便在用戶的shell上顯示它。 我必須使用管道IPC來交換父級和子級進程之間的數據。在c編程中使用管道

我的代碼如下

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <signal.h> 
#include <string.h> 

void sendNumber(int); 
void RecResult(); 
int f_des[2]; 

int main(int argc, char *argv[]) 
{ 
    static char message[BUFSIZ]; 
    if (pipe(f_des) == -1) 
    { 
     perror("Pipe"); 
     exit(2); 
    } 
    switch (fork()) 
    { 

     case -1: perror("Fork"); 
      exit(3); 

     case 0: /* In the child */ 
     { 

      // read a meesage 
      close(f_des[1]); 
      read(f_des[0], message, BUFSIZ ); 

      int num=atoi(message); 
      printf("Message received by child: [%d]\n", num); 


      if(num % 2 == 0) 

       sprintf(message,"%d is Even \0",num); 

      else 

       sprintf(message,"%d is Odd \0",num); 

      close(f_des[0]); 
      write(f_des[1], message, BUFSIZ); 
      exit(0); 
     } 

      break; 
     default: /* In the parent */ 
     { 
      int num; 
      printf("\n Enter an Integer \n"); 
      scanf("%d",&num); 
      char msg[BUFSIZ]; 
      sprintf(msg,"%d",num); 

      // write a message 
      close(f_des[0]); 
      write(f_des[1], msg, BUFSIZ); 

      printf("\n Waiting Child \n"); 

      wait(NULL); 
      // read a mesaage 
      static char message[BUFSIZ]; 
      close(f_des[1]); 
      read(f_des[0], message, BUFSIZ); 

      printf("========> Result: %s . \n",message); 
     } 
    } 
} 

如圖孩子成功接收的消息,但家長不接受任何結果:S 任何一個能幫助 這裏是我的輸出

[email protected]:~$ gcc -o test_3 test_3.c 
[email protected]:~$ ./test_3 

Enter an Integer 
3 

Waiting Child 
Message received by child: [3] 
========> Result: . 
[email protected]:~$ 

所有;)

+2

你是否意識到你在子節的開始處關閉了(f_des [1])',然後進入'write(f_des [1],message,BUFSIZ);'在所有相同的末尾?同樣的問題在父節中,但用於讀取和'f_des [0]'。 – WhozCraig

+3

如果父母正在向孩子寫入數據,並且孩子將數據寫入父母,則需要兩個管道。 –

+0

^^^^ ----他說的。更重要的是,兩個管道*組*。 – WhozCraig

回答

1

PIPE通道是一個單向通信通道。如果您希望子進程回寫到父進程,則需要第二個PIPE通道,與用於從父進程接收消息的通道不同。