Reputation: 1188
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:
the output I get is kind of weird:
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
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