FinalDestiny
FinalDestiny

Reputation: 1188

fork and pipes not working out well, they execute at the same time

Here's the piece of code I currently have:

 int main () 
  {
  int pid, fd[2], i;
  char comanda[1000], *var, vect[100][100], text[100];
  if((pid = fork()) < 0 )
  {
    perror("fork error");
    exit(1);
  }
  if(pid){ 
      printf("enter command: \n");
      scanf("%[^\t\n]", comanda);
      close(fd[0]);
      close(0);
      var = strtok(comanda, " ");
      i=0;
      while(var != NULL)
      {
        strcpy(vect[i], var);
        var = strtok(NULL, " ");
        i++;
      }
      if(strcmp(vect[0], "login") == 0)
      {
          write(fd[1], "login", 5);
          printf("I got login");
      }
      close(fd[1]);
      wait(NULL);
  }
  else
  {
      close(fd[0]); 
      int i=0;
      read(fd[0], &text, sizeof(text));
      printf("This is the child ");
      exit(0);
  }
  return 0;
} 

while the expected output would be:

  1. Enter command:
  2. I enter command here-
  3. he writes in the pipe
  4. he writes "I got login"
  5. he goes in the child and processes my text

the output I get is kind of weird:

  1. "Enter command:" from parent... then
  2. "This is the child" from the child ?!?!?! from where?!?!
  3. asks the input, the scanf
  4. writes "I got login" from the parent.

This is kind of weird, all I want is to read something in the parent, write in the pipe and send it to the child process which should actually do something with that value.

Upvotes: 0

Views: 225

Answers (1)

Dale Hagglund
Dale Hagglund

Reputation: 16480

Nowhere do you initialize the fd array so that it actually contains valid file descriptors. The child's call to read therefore fails immediately with an invalid file descriptor (you should be checking return codes of all system calls), which explains the "unexpected" output from the child.

In the parent (ie, before calling fork) you need to initialize fd as follows:

pipe(fd);

and delete

close(fd[0]);

from the child, since you need to read from that fd.

Upvotes: 2

Related Questions