B
B
Billy Milligan2015-10-28 03:08:49
linux
Billy Milligan, 2015-10-28 03:08:49

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));
        }

2
PS program: I set the descriptors to 3 and 4.
I do this because I saw how the descriptor is passed to the second program as a parameter.
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:");

The second program outputs: bad file descriptor.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2015-10-28
@Billy_Milligan

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.

O
Oleg Tsilyurik, 2015-10-28
@Olej

The second program outputs: bad file descriptor.

Here is the solution to all your problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question