Given this code :
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world! I'm the son and this my message!\n";
char readbuffer[80];
pipe(fd); // piping fd[0] & fd[1]
if((childpid = fork()) == -1) // here we create a SON process
{
perror("fork");
exit(1);
}
if(childpid == 0) // child process
{
/* Child process closes up input side of pipe */
close(fd[0]); // closing the READ end from reading , after that the SON would write into fd[1]
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
printf("Verification : Message was sent successfully by the SON!\n");
exit(0);
}
else // father process
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("I'm the father and I received that string: %s", readbuffer);
}
return(0);
}
The output is :
I'm the father and I received that string: Hello, world! I'm the son and this my message!
Verification : Message was sent successfully by the SON!
I’m trying to understand pipes , and few things are not clear to me :
-
If the son sends his message in that line
write(fd[1], string, (strlen(string)+1));and after that we have theprintfthat verifies that the message was sent, why am I getting the verification (e.g.Verification : Message was sent successfully by the SON!) after the father received the message from the son ? wasn’t it suppose to be first the verification from the son and only then the string ?
-
If the father tries to read from the pipe and the son want to write to the pipe , somewhere here hides (I think) a deadlock , doesn’t ? why am I not getting a deadlock ?
Thanks
1) The reason the message from the child process comes later is because writing to a pipe can block until there is sufficient space in the buffer (from here):
So in other words the child process waits for the parent process to read the message within the call to
write().2) If the child process fails to write anything to the pipe, then yes the parent will block (it won’t deadlock as such).