Ariel Capozzoli
Ariel Capozzoli

Reputation: 795

C programming bi directional communication

I am trying to make something work here, I have c program where my parent process creates a pipe so he can listen for request from children processes. These children are created dynamically, it is never the same number. So far, I managed to send the requests to the parent through the pipe, and have it synchronized through mutex.

My problem is, this request need an answer provided to the child that made such request, and I can't use the same pipe since its one way, and all the other children will be using it (I already tried and it generates a serious issue)

The next thing I tried was making a pipe before the request on the child and passing the value of the descriptor in the request. Also failed, since the parent doesn't know those descriptors, which I found out after failing.

So now I am clueless in how to make that request response reach the child... I am a beginner with C programming, so, all help is welcomed!

BTW: working in a Unix program, pure C programming

Upvotes: 3

Views: 1615

Answers (1)

Ali Seyedi
Ali Seyedi

Reputation: 1817

Pipes are uni-directional and using sockets seems painful for a little ipc thing.

I recommend you to use socketpair(). You can consider them as bi-directional pipes.

Here is an example where the parent sends a character to its child.Then child makes it uppercase and sends it back to the parent.(It is from beej's tutorial)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(void)
{
    int sv[2]; /* the pair of socket descriptors */
    char buf; /* for data exchange between processes */

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        perror("socketpair");
        exit(1);
    }

    if (!fork()) {  /* child */
        read(sv[1], &buf, 1);
        printf("child: read '%c'\n", buf);
        buf = toupper(buf);  /* make it uppercase */
        write(sv[1], &buf, 1);
        printf("child: sent '%c'\n", buf);

    } else { /* parent */
        write(sv[0], "b", 1);
        printf("parent: sent 'b'\n");
        read(sv[0], &buf, 1);
        printf("parent: read '%c'\n", buf);
        wait(NULL); /* wait for child to die */
    }

    return 0;
}

Also you can easily use two pipes for your two directions.

Upvotes: 6

Related Questions