I am using these two programs of this answer. This answer uses named-pipes and not pipes, am I correct?
I have written main.c, which is actually the code of my actual project, minimized to this specific question (that's why I have a for loop for example).
#include <unistd.h>
#include <sys/wait.h>
#include <stddef.h>
#include <limits.h>
#include <stdio.h>
int main(void) {
pid_t pid;
int i;
for(i = 0; i < 2; ++i) {
pid = fork();
if (pid == -1) {
// error, failed to fork()
perror("failed to fork()");
return 1;
} else if (pid == 0) {
// child code
if(i < 1) {
// the writer.c
char* arg_list[] = { "w", NULL };
execv( "w", arg_list );
printf("exec FAILED\n");
} else {
// the reader.c
char* arg_list[] = { "r", NULL };
execv( "r", arg_list );
printf("exec FAILED\n");
}
}
}
// parent code
int status;
// wait for all children to terminate
while ((pid = wait(&status)) > 0) {
if (status == 1) {
printf("The child process terminated with an error!\n");
return -1;
}
}
printf("All children are done\n");
return 0;
}
The problem is that sometimes, the reader receives garbage (or most likely nothing) and it hangs up.
Sample output:
Received: Hi
All children are done
samaras@samaras-A15:~/test$ ./m
Received: Hi
All children are done
samaras@samaras-A15:~/test$ ./m
Received: <----------------- This is garbage, that is not reproducible
^C
So, what am I missing?
No need to read below that point.
My guesses are (not checked, so if I am correct, I still need clarification):
The reader runs before writer, that's why it has garbage, but then why it hangs?
or
I need to write a wrapper function read_all()
(and one for the write case as well?) that collects all the data that the pipe spits, but then why if I replace "Hi" with "H", I have the same behaviour?
EDIT:
In case my first guess is the case, I put a loop for reading, but it will execute forever in the case that reader starts first.
In the case that I see garbage, after running with strace -f
I got this:
...
[pid 3326] read(-1, 0xbfddd80c, 1024) = -1 EBADF (Bad file descriptor)^C
Process 3324 resumed
Process 3325 detached
Process 3326 detached