使用管道进行过程通信

时间:2010-11-08 14:24:25

标签: c linux pipe fork

我在linux中使用c管道时遇到了问题。我的工作如下:

在c中编写一个程序,它将创建一个孩子。子进程将使用管道与父进程通信。父进程将给出0 = y之间的随机数,然后父亲将向用户询问他的姓名,并且他将这样发布(George - > egroeG)。

我的代码如下:

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

void myalarm(int sig) {
 printf("\nTime is out. Exiting...\n");
 exit(0);
}
int main(int argc, char **argv){

   int x, x1, n, m, pid, fd1[2];
   int y = rand() % 100 + 2;
   int i=0;
   char *name, *arxi;

 if (pipe(fd1) == -1) {
  perror("ERROR: Creating Pipe\n");
  exit(1);
 }
  pid = fork();
   switch(pid) { 
    case -1:
     perror("ERROR: Creating Child Proccess\n");
     exit(99);
    case 0:
     close(fd1[0]);   /*Writer*/
     printf("\nGive a number between 1 & 100:\n");
     scanf("%d", &x);

     n = write(fd1[1], x, 1);
/*dup2(fd1[0],0);*/
      while (x < 0 || x > 100) {
       printf("ERROR:You gave a wrong number...");
       printf("\nGive a number between 1 & 100:\n");
       scanf("%d", &x); 
      }
     close(fd1[1]);
     break;
    default:
     close(fd1[1]);   /*Reader*/
     printf("I Am The Father Process...\n");
     printf("y = %d\n", y);

     m = read(fd1[0], x1, 0);
/*dup2(fd1[1],1);*/   close(fd1[0]);

      if (x1 < y) {
       kill(pid, SIGTERM); //termination of the child process

      }
      else {
       signal(SIGALRM, myalarm); 
       printf("Please, type in your name:\n");
       fflush(stdout);
       alarm(10);   //Start a 10 seconds alarm
       scanf("%s", name);
       arxi = name;
       alarm(0);
        while(*name != '\0') {
         name++;
        }
        name--;
        while(name >= arxi) {
         putchar(*name);
         name--; 
        }
       printf("%s\n", name); 
      }
     wait(&pid);
     break;
   }
return 0;
}

1 个答案:

答案 0 :(得分:0)

可能还有其他问题,但这些问题都是错误的:

n = write(fd1[1], x, 1);

这将从地址x写入1个字节,这可能会崩溃。你想要:

n = write(fd1[1], &x, sizeof(x));

类似地,这将读取0个字节以寻址x1,这将无效:

m = read(fd1[0], x1, 0);

你想要:

m = read(fd1[0], &x1, sizeof(x1));