2013-10-07 31 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通道,与用于从父进程接收消息的通道不同。