Pipe & Fork problem :(

Hi, I'm kinda new to multithreading in general, but I know the basics.
In the code below I'm trying to send some messages between the child and the parent, but... it's not working. What's wrong with what I'm doing?
p.s. It works... sometimes

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
36
37
38
39
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>

void poip()
{
 int filedes[2];
 const int bsize = 100;
 char buf[bsize], buf2[bsize];
 int status;
 
 status = pipe(filedes); if(status == -1) printf("pipe error\n");
 if(fork()) { //parent
   close(filedes[1]);
 
   if(read(filedes[0],buf,bsize)) printf("|%s|\n",buf);
   if(read(filedes[0],buf2,bsize)) printf("|%s|\n",buf2);

   close(filedes[0]);
   wait(NULL);
   exit(0);
  }
 else { //child
   close(filedes[0]);
   
   write(filedes[1],"hola",5);
   write(filedes[1],"hello",6);
  
   close(filedes[1]);
   exit(0);
  }
}

int main()
{
 poip();
}
pipes are stream-oriented, not packet-oriented.

The first read (line 18) is reading all 11 bytes, which include an embedded newline.

A simple strace shows the problem. Here's an excerpt:


close(4)                                = 0
read(3, "hola\0hello\0", 100)           = 11   <<<----------- right here
fstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7feb000
write(1, "|hola|\n", 7|hola|
)                 = 7
read(3, "", 100)                        = 0
close(3)                                = 0
wait4(-1, NULL, 0, NULL)                = 23292
exit_group(0)                           = ?


Last edited on
Thank you :D
Topic archived. No new replies allowed.