Search code examples
cubuntupipeforksystem-calls

Program stuck on read() using Pipe() in c


My code is as follows: I am using pipe system call in c language. Here my program is stuck on read(the_pipe_1[0],recieved,20); before line: printf("DUCKKKKKK\n");

The output is :

In parent 
Enter the value
In Child

The code:

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include<sys/wait.h>

int isPalindrome(char str[]);

int main(int argc, char const *argv[]) {

int the_pipe_1[2];
int the_pipe_2[2];

char recieved[20];
char input[20];
char pal[10];
int palchid;

int  pipeVal = pipe(the_pipe_1);
if (pipeVal == -1 ) {
   printf("Pipe 1 failed\n");
 }
if (pipe(the_pipe_2) == -1 ) {
   printf("Pipe 2 failed\n");
 }

 int forkVal =  fork();

 if (forkVal > 0) {
    printf("In parent \n");
    close(the_pipe_1[0]);
    printf("Enter the value\n");
    gets(input);
    write(the_pipe_1[1],(char) input,20);

    wait(NULL);
    close(the_pipe_2[1]);
    read(the_pipe_2[0],pal,10);
    if(pal == "0")
    {
       printf("Not plaindrome\n");
    }
    else
       printf("Plaindrome\n");

     }


  else if(forkVal == 0)
  {
     printf("In Child\n");
     close(the_pipe_1[1]);

     read(the_pipe_1[0],recieved,20);
     printf("DUCKKKKKK\n");

     printf("Val of recieved %s \n",&recieved );

     palchid = isPalindrome(recieved);
     close(the_pipe_2[0]);
     write(the_pipe_2[1],(char)palchid,10);


   }
   return 0;
 }

int isPalindrome(char str[])
{
   int l = 0;
   int h = strlen(str) - 1;

   while (h > l)
   {
      if (str[l++] != str[h--])
      {
        return 0;
      }
   }
return 1;
}

Solution

  • simple. change the line to:

    write(the_pipe_1[1], input, 20);
    

    and it works fine.

    Explanation: When you cast input(which is usually a 32bit pointer) to char(which is 8 bit) you created a pointer to an illegal address. On some accesses, this would cause segmentation fault. For instance, you can try:

    //segmentation fault
    printf("input - %s\n", (char)input);
    

    but for write(), which works differently(didn't delve into why), this caused the program to get stuck instead

    PS. this row will never be true:

    if(pal == "0")