0
votes

I 've got a problem using pipes in c for linux. My work is the following:

Write a program in c, which will create a child. The child process is going to communicate with the father process using pipe. The father process will give a random number between 0=y then the father will ask from the user his name and and he will post it like this (George -> egroeG).

My code is the following:

   #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
Because my english isn't that good, give me something in c. - Konst
Please edit your post and put all code in the code format. - Nico Huysamen
@0xA3: Edit conflict, sorry. I suspect we made the same change (i.e. fixing code formatting), though I also altered tags/title. - Brian
@Konst: What is wrong with the code you have now? - Brian
the little parts are all working one by one, but i need to use the pipe communication between father and child communication - Konst

1 Answers

0
votes

There may be other problems, but these jump out as wrong:

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

This is going to write 1 byte from address x, which will probably crash. You want:

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

Similarly, this is going to read 0 bytes to address x1, which will do nothing:

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

you want:

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