简体   繁体   中英

Get file descriptor of stdout c

stdin, stdout, stderr file descriptors are 0, 1 and 2 by default. However after I open a file by fd = open(foo, 0) , I find fd now is 1. 1 is used for the new file descriptor. What is stdout file descriptor now? Or it is closed and I need to reopen it? If yes, how? Is there a way to keep 0, 1, 2 file descriptors and use from 3?

/* readslow from the book with my "improve": the unix programming environment */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 512
int main (int argc, char *argv[])
{
    char buf[SIZE];
    int n, fd;
    int t = 10;

    if ((argc > 1) && (fd = open(argv[1], 0) == -1)) {error("can't open %s", argv[1]);}
    fprintf(stderr, "%d", fd);

    for (;;) {
        while ((n = read(fd, buf, sizeof buf)) > 0)
           write(1, buf, n);
        sleep(t);
    }
}

fprintf(stderr, "%d", fd) will give me 1.

[ There was no code in the Question when this Answer was composed. I had accepted the OP's claim that the file descriptor returned by open was 1 , which turns out to be untrue due to a misplaced paren. ]

I find fd now is 1. 1 is used for the new file descriptor.

The only way that would happen is if you closed fd 1.

What is stdout file descriptor now?

fileno(stdout) will give you the fd associated with the handle.

Is there a way to keep 0, 1, 2 file descriptors and use from 3?

If you don't close fd 0, 1 and 2, they won't be reused. open uses the lowest-numbered unused file descriptor.

If you wish to disconnect fd 0, 1 or 2, don't close them. That causes all sorts of problems. Re-open them to /dev/null instead.

Or it is closed and I need to reopen it? If yes, how?

You can use dup2 to make an fd an alias of another one.

Your code contains the fragment:

if (argc > 1 && (fd = open(argv[1], 0) == -1))

The result in fd is as if you'd written the comparison inside parentheses:

if (argc > 1 && (fd = (open(argv[1], 0) == -1)))

So the result assigned to fd is correctly 1 because the value returned by open() is indeed -1 . You should have parentheses around the assignment:

if (argc > 1 && (fd = open(argv[1], 0)) == -1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM