concurrencyboy
concurrencyboy

Reputation: 371

redirect pipe's read end to a file descriptor

I have two child processes they share their parent's common pipe descriptors. There is no problem for closing ends etc. The problem is I wish to redirect pipe's read end to a file descriptor instead of holding a buffer and writing the buffer's content to a file. Is it possible? My code snippet as follow

// we're sure we can read from fd[0], I did it sucessfully
// I mean there is no problem about the communication

int open_fd = open(filename, O_WRONLY|O_CREAT, 0666);
if (dup2(open_fd,fd[0]) == -1) {
    perror("error ");
    return 1;
}
if (close(open_fd) == -1) {
    perror("close error");
    return 1;
}

When I did the above code, I doesn't write into the file called as filename. By the way, is there a need to close open_fd by calling close(open_fd)? Since dup2 closes it already.

Upvotes: 0

Views: 1132

Answers (2)

John Bollinger
John Bollinger

Reputation: 180201

When I did the above code, I doesn't write into the file called as filename.

Of course not. When you call dup2(open_fd,fd[0]), you make the integer value stored in fd[0] refer to the same file that open_fd does, but that has to has nothing directly to do with what happens to bytes fed into the write end of the pipe. It affects them only indirectly, by causing the file descriptor number whose value was initially stored in fd[0] to first be closed if it is open.

A file descriptor is basically a key to a table mapping integers to open file descriptions in the kernel. dup2() changes what open file description the target FD is mapped to; it does not modify the open file description itself or affect its semantics, and it's at that level where the pipe lives.

Bytes written to the write end of a pipe are obtained from the read end of the pipe by reading it. However you do that, they initially reside in memory and / or in CPU registers. To make them go from there to a file, you need to send them there. For example, you might set up a thread whose purpose is to read whatever bytes are available from the pipe, and then writes them to your file.

Upvotes: 0

r3mus n0x
r3mus n0x

Reputation: 6144

You've probably misunderstood the purpose of dup2. It just changes "the meaning" of the file descriptor, so that it now "points" to the same stream as the other descriptor. But it doesn't in any way transfer data from one file descriptor to another. To actually achieve what you want you can try splice:

int open_fd = open(filename, O_WRONLY|O_CREAT, 0666);
splice(fd[0], NULL, open_fd, NULL, size, 0);

Note that you'll have to specify how much data you want to transfer (size variable in above example).

Upvotes: 1

Related Questions