Ricky
Ricky

Reputation: 705

Connecting output of one pipe to input of one FIFO

I am trying to write a client-server program in which there are three executables D1, D2 and D3 which provide some data as the output. The clients request for any one of these data sources and send their pid to the server with the help of a common fifo. The structure for sending this request is:

struct Request
{
    char p[10]; // the pid of the client program in string form
    int req; // 1,2,or 3 depending on which one is required D1,D2 or D3
};

After getting a request the server will open a fifo whose pathname is the pid of the client. So it works as a client specific fifo.

mkfifo(pid,O_CREAT|0666);
int fd1 = open(pid,O_WRONLY);

Now, suppose the req field is 1. If it is the first request for D1, the Server will run:

FILE* fp = popen("./D1","r");
int fd = fileno(fp); //for getting the file descriptor for the reading end of the pipe connected to D1

Now I want my client to read from the pipe of D1.D1 contains simple logic program like:

while(1)
{
    write(1,"Data from D1",12);
    sleep(1);
}

I tried dup2(fd,fd1) but it did not work. Is there any way connecting the two file descriptors fd and fd1?

Also, if another client requests for D1, how to connect the file descriptor of client2 to fd so that both clients receive the same message together?

Upvotes: 0

Views: 172

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136296

Instead of "connecting" two file descriptors, you can send the file descriptor to the client and let the client read:

  1. The server listens on a UNIX stream socket.
  2. The client connects the socket and sends the request.
  3. The server receives the request, does popen and obtains the file descriptor.
  4. The server then sends the file descriptor to the client and closes the file descriptor.
  5. The client receives the file descriptor and reads from it till EOF.

See man unix(7) for details about sending file descriptors between processes with SCM_RIGHTS.


Alternatively, instead of using popen:

  1. The server forks itself. The child does mkfifo (the client passed the filename in the request), opens it for write and redirects its stdout into the named pipe's file descriptor.
  2. The child execs the application. This application writes into stdout and that goes into the named pipe.
  3. The client opens the named pipe and reads the output of the application. The client can unlink the pipe filename after opening it.

Upvotes: 1

Related Questions