0

Part of my bigger project is using pipes to communicate with 2 processes.
P1 process generates numbers, converts them to hex and next sends them through pipe to P2 process.
P2 prints the numbers.

pipe1.c

#define WRITE 1
#define READ 0
int main() {
int i;
char hex[30];
int my_pipe[2];
pipe(my_pipe);  
int var;        
            close(my_pipe[READ]);
            for(i=50;i<100;i++){
                printf("P1 generated: %d\n",i);
                sprintf(hex, "%x", i);
                write(my_pipe[WRITE], &hex, sizeof(hex));
                printf("P1 in hex %s\n",hex);
                sleep(3);

                }

    return 0;
}

pipe2.c

#define WRITE 1
#define READ 0


int main() {
char hex[30];
int my_pipe2[2];
pipe(my_pipe2);
int var;        

            close(my_pipe2[WRITE]);
            for(;;){
            read(my_pipe2[READ], &hex, sizeof(hex)); 
            printf("P2 received:  %s",hex);
            sleep(3);
            }


    return 0;
}

All processes are just started by my main project file:

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


//.....
    if (fork() == 0) {
        execlp("./pipe1", "./pipe1", NULL);
    }
sleep(1);
    if (fork() == 0) {
        execlp("./pipe2", "./pipe2", NULL);
    }
sleep(1);
//....
}

Can someone can help me and tell me where I make an error?
I tried many things but without result.
I just got one print:

P1 generated
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Adrian
  • 482
  • 5
  • 20
  • How do you think that pipe1.c needs to talk to pipe2.c - there is nothing in the code to indicate this – Ed Heal Jan 13 '18 at 22:41
  • 2
    The main launcher program needs to create the pipe and the post-fork code will sort out the connections so `pipe1` writes to its standard output and `pipe2` reads from its standard input. As it stands, the processes have two unrelated pipes. – Jonathan Leffler Jan 13 '18 at 22:46
  • 4
    Normally, a single process will call `pipe` and then `fork` so that both the parent and the child hold ends of the pipe. If you call `pipe` and then close one end of the pipe without `fork`ing...well, that's just kind of pointless. – William Pursell Jan 13 '18 at 22:47
  • Possible duplicate of [Pipes and Forks in C](https://stackoverflow.com/questions/40711311/pipes-and-forks-in-c) – Ahmed Masud Jan 13 '18 at 23:53
  • An alternative would be for the processes to used a "named pipe" (aka FIFO)... that way pipe1 & pipe2 don't have to have the same parentage. – TonyB Jan 14 '18 at 01:02

0 Answers0