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:
- Enter command:
- I enter command here-
- he writes in the pipe
- he writes “I got login”
- he goes in the child and processes my text
the output I get is kind of weird:
- “Enter command:” from parent… then
- “This is the child” from the child ?!?!?! from where?!?!
- asks the input, the scanf
- 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.
Nowhere do you initialize the
fdarray so that it actually contains valid file descriptors. The child’s call toreadtherefore 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 initializefdas follows:and delete
from the child, since you need to read from that fd.