cici30725
cici30725

Reputation: 21

Why using dup(1) before close(1), open("/dev/stdout", O_WRONLY) results in "No such file"?

Problem is same as the title, the OS is linux. I've tried a few examples.

dup(1);
close(1);
int fd = open("/dev/stdout", O_WRONLY);

This caused a "/dev/stdout No such file" error.

I thought a file descriptors is just a index to a pointer array that points to a struct file, and close() would clear the resources if no fd is referencing that struct file. If I use dup(1), shouldn't it create a fd 3 pointing to what fd 1 was pointing, so that close(1) doesn't clear /dev/stdout?

Then I tried

int tmp = dup(1);
close(1);
dup(tmp, 1);
int fd = open("/dev/stdout", O_WRONLY);

And this worked.

I'm think I'm missing some core concepts. Any help is appreciated, thank you.

Upvotes: 2

Views: 278

Answers (1)

David Schwartz
David Schwartz

Reputation: 182819

You closed stdout and then attempted to open it. But you had already closed it, so there was nothing to open. If you have no stdout, because you've closed it, then /dev/stdout doesn't exist.

I'm curious what you expected this to return.

Upvotes: 2

Related Questions