Reputation: 344
I write this code for pipe() between child and parent process. I need to ensure whether this is a correct code or not. By the way it's gives the answer what is suppose to see !
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
pid_t pid;
int fd[2];
char buf[20];
pipe(fd);
switch(pid = fork()){
case -1:
perror("pipe");
exit(1);
case 0:
/*child process*/
close(fd[1]);
read(fd[0], buf, 20);
printf("Child read message from parent: %s\n", buf);
exit(1);
break;
default:
/*parent process*/
close(fd[0]);
write(fd[1], "Hello from parent\n", 17);
break;
}
return 0;
}
Upvotes: 4
Views: 9224
Reputation: 34829
The switch
statement is mostly ok, although you don't need the pid
variable since you don't do anything with it.
The parent code is also mostly ok, but the string is actually 18 bytes without the NUL terminator, and 19 bytes with the NUL terminator. It's good practice to handle the newline and NUL terminator in the child, so I would stick with 17 and remove the newline from the string.
The child code is wrong. You need a variable to store the return value from read
. You need to check the return value to make sure the read
succeeded. And you need to add a NUL terminator to the string. In the C programming language, a "string" is an array of characters that ends with a zero byte (called the NUL terminator, and written as '\0'
). It's your job to make sure that the buffers you use are always big enough to hold the NUL terminator, and that every string has a NUL terminator.
So the fixed code looks like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main( void )
{
int fd[2];
char buffer[20];
if ( pipe(fd) < 0 ) {
perror( "pipe" );
exit( 1 );
}
switch( fork() ) {
case -1:
perror( "fork" );
exit( 1 );
case 0:
/*child process*/
close(fd[1]);
ssize_t count = read( fd[0], buffer, sizeof(buffer)-1 );
if ( count <= 0 ) {
perror( "read" );
exit( 1 );
}
buffer[count] = '\0';
printf( "Child read message from parent: %s\n", buffer );
exit(1);
default:
/*parent process*/
close(fd[0]);
char *message = "Hello from parent";
size_t length = strlen( message );
write( fd[1], message, length );
break;
}
return 0;
}
Upvotes: 5