繁体   English   中英

使用管道进行过程通信

[英]Using pipes for process communication

我在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;
}

可能还有其他问题,但这些问题跳错了:

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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM