Special handling of /dev/null in open and write?
Asked Answered
B

1

2

according to a hint from another thread I want to analyze pointers, if their dereferencing would cause an segmentation faults or not. The idea is to write code like this:

bool IsPointerValid( void* pPointer )
{
    // when opening "/tmp/hugo" here, it works fine... but not with /dev/null??
    int iFD = open( "/dev/null", O_WRONLY );
    int iBytesWritten = write( iFD, pPointer, 4 );
    close( iFD );

    return iBytesWritten > 0;
}

But whatevery I pass to IsPointerValid(..), it returns always true - because iBytesWritten is always 4. But when opening "/tmp/testfile" or a fifo, it works like expected: Passing the NULL pointer to write(..), it returns -1.

What is the reason for this special treating of "/dev/null"?

Thanks,

Charly

Bijouterie answered 17/2, 2011 at 13:35 Comment(0)
K
5

Because it's a special file, so it brings its own definition of read and write. (The linux kernel implements polymorphism using function pointers in the driver layer). Apparently the version of write provided by the /dev/null device doesn't use the pointer you pass in.

Killifish answered 17/2, 2011 at 13:38 Comment(6)
Hmmm... but that's bad. How can I workaround this problem, without creating a temporary file?Bijouterie
Since you want to find out if dereferencing a pointer would cause a segfault, why not just dereference it and handle the segfault if one occurs? No file is needed for that.Killifish
I prefer, to check the pointers in advance - since it's just straightforward and easy to understand.Bijouterie
@Charly: How do you think that write (to a normal file) returns EFAULT? It traps the segfault.Killifish
@BenVoigt: Yes, I just wrote a demo app, and it was working. I'm not sure if it was EFAULT - but the strerror() returned some similar text...Bijouterie
@Charly: It's actually errno that would be EFAULT, the return value from write should be -1. If you really want to use the write function rather than signal or sigaction then you can get a file descriptor from pipe or socketpair.Killifish

© 2022 - 2024 — McMap. All rights reserved.