Search code examples
cprintingpipeforkmessage

Getting unwanted characters at the end of a message


The following c program is used to send a message from parent process to the child process(created using fork()) via a pipe and is run on the linux terminal!

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc,char *arg[]){
    pid_t child;
    int pipefd[2];
    int ret;
    char message[20];
    ret =pipe(pipefd);


          if((child=fork())==0){
                              printf("The child process \n");
                              close(pipefd[0]);
                                   write(pipefd[1],"Hello from parent",17);

                              }

                              else{
                                   close(pipefd[1]);
                              read(pipefd[0],message,17);
                              printf("Message from parent %s\n",message);
                                   }
                                   return 0;
                                   }

The above code prints the message "Hello from parent" but at the end of parent part an @ sign is printed! what is the reason and how can i rectify it?


Solution

  • Send also null character that is at the end of the string. Same for reading.

    write(pipefd[1],"Hello from parent",18);