簡體   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