Reputation: 705
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
Reputation: 136296
Instead of "connecting" two file descriptors, you can send the file descriptor to the client and let the client read:
popen
and obtains the file descriptor.See man unix(7) for details about sending file descriptors between processes with SCM_RIGHTS
.
Alternatively, instead of using popen
:
fork
s itself. The child does mkfifo
(the client passed the filename in the request), open
s it for write and redirects its stdout
into the named pipe's file descriptor. exec
s the application. This application writes into stdout
and that goes into the named pipe.unlink
the pipe filename after opening it.Upvotes: 1