Answer the question
In order to leave comments, you need to log in
How to work with PIPE?
It is not possible to transfer the structure through PIPE to another program. There are many examples on the Internet with fork(), but it is impossible to do the same for 2 different programs.
1 program:
int pipefd[2], rs;
my_struct pipe_msg;
char buf[sizeof(my_struct)];
rs = pipe(pipefd);
printf("pipe1 = %i, pipe2 = %i\n", pipefd[0], pipefd[1]);
if(rs < 0) {
printf(" *PIPE [ ERROR ]\n");
return -1;
}
printf(" *PIPE [ OK ]\n");
close(pipefd[1]);
while(1) {
read(pipefd[0], buf, sizeof(my_struct));
if (strcmp("",buf)!=0)
{
memcpy(&pipe_msg, &buf[0], sizeof(my_struct));
}
memset(buf, 0, sizeof(buf));
}
int rs;
my_struct pipe_msg;
char buf[sizeof(my_struct)];
int pipefd[2] = {3,4}; //так как и в программе 1, дескрипторы всегда тоже 3 и 4
pipe_msg.val1 = 2;
pipe_msg.val2 = 3;
memcpy(&buf[0], &pipe_msg, sizeof(my_struct));
write(pipefd[1], &buf, sizeof(my_struct));
perror("Write:");
Answer the question
In order to leave comments, you need to log in
It won't work like this. File descriptors are local to processes. With fork, the children inherit the parent's open file descriptors, so everything works. You can solve this problem , but no one does. It is better to use another method of communication.
named pipes
Or unix, tcp or udp sockets whichever you want.
The second program outputs: bad file descriptor.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question