Reputation: 59
I am having some difficulties in the following thing:
I am trying to send a pipe to a child node within a function, and then have the child writing into it.
The following code parts will explain it better:
int p[2];
int i;
pipe(p);
close(p[1]);
if(fork1() == 0){
close(p[0]);
runcmd(parsecmd(buf),p);
}
wait(0);
}
while(read(p[0],&i,sizeof(int)) != 0){
printf(1," id: %d\n",i );}
and runcmd will have the following code:
...
void runcmd(struct cmd *cmd,int pp[]){
int j = getpid();
write(pp[1],&j,sizeof(int));
close(pp[1]);
...
sadly the expected result should be - the parent will print the id (getpid is a function that returns the current running process id ), but it doesn't, it prints nothing when evokes. what did I do wrong?
Upvotes: 0
Views: 345
Reputation: 59
the problem has been solved!
the troublesome part was the fact the while loop was after the "wait" call, and not before, after changing that it worked like magic!
thanks for the help!
Upvotes: 0
Reputation: 9894
You close the write side of the pipe before forking so the child process can't write to it. You also need to exit()
the child. So your code should be sth. like that:
pipe(p);
if(fork1() == 0){
close(p[0]);
runcmd(parsecmd(buf),p);
exit(0);
}
close(p[1]);
...
Besides I would recommend to add some error handling (fork()
may also return -1)`
Edit: this works on Linux
void runcmd(int pp[])
{
int j = getpid();
write(pp[1],&j,sizeof(int));
close(pp[1]);
exit(0);
}
int main( int argc, char *argv[] )
{
int p[2];
int i;
int status;
pipe(p);
if(fork() == 0){ // for linux: fork() instead of fork1()
close(p[0]);
runcmd(p);
}
close(p[1]); // close belongs here
wait(&status); // Linux: wait(0) is not allowed
while(read(p[0],&i,sizeof(int)) > 0) // != 0 causes endless loopn on EOF
{
printf(" id: %d\n",i ); // first parameter '1' doesn't belong there
}
return( 0 );
}
Upvotes: 1