Problem with write()/read() function using pipes in Linux

Hello,

I am facing some difficulties with the pipes, I cannot send the complete input to the receiving parent.

Tried different ways but I am unable to figure out a solution

Here is a code example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include<iostream>

using namespace std;

int main()
{ 
   int fd[2]; //declare the file discriptor
   char x[100],y[100];
   pipe(fd);  //create a pipe
   int a  = fork();
   if(a == 0)//child
   {
     cout<<"Enter a string: ";
     cin>>y;
     close(fd[0]);//close the read end
     write(fd[1],y,strlen(y)+1);
     exit(0);
   }
   else
   {
      wait(NULL);
      close(fd[1]);
      int no = read(fd[0],x,strlen(x));
      cout<<"Recieved string: "<<x<<"\n";
      cout<<"no of bytes: "<<no<<"\n";
   }
   
   return 0;
}

So my problem is in the write function, only the first character is sent.
I tried to change x, y to strings and then use string.c_str() but doesn't work.

I also tried to take input and store them in a string variable, then I copy them to the character array using loop but also it did not work.

How can I write the complete set of characters in the array to the pipe?

I apologize for my poor explanation.
Last edited on
1. What does the text look like before write?

2. Try getline instead of >>
http://www.cplusplus.com/reference/istream/istream/getline/
Topic archived. No new replies allowed.