Let's assume that I have a file descriptor which is shared among several threads. One thread is currently writing to or reading from it, and also let's assume that this operation is "really slow" (for example it's not a regular disk file, maybe it's an UART terminal on embedded device).
int ret = read(sharedFd, buffer, sizeof(buffer));
Now another thread in closing this shared file descriptor:
int ret = close(sharedFd);
To make it more tricky, let's assume that the thread that does reading/writing was suspended just after it translated the sharedFd
index into system's file structure, but before it actually starts the operation (it has the handle to the underlying object, but did not start using it yet). I know that this is a very bad practice, generally not a good code and so on, and so on. But I'm more interested in answer to the following question:
Does any standard (POSIX, C, ...) - directly or indirectly - say that such use case is "undefined behavior"?
The reason for my question is not because I want to write code like that and want to know whether it's good or how to fix it (I know it's generally bad and should be improved by using synchronization like a mutex or semaphore). I'm asking because I'm writing a RTOS for microcontrollers and currently I'm implementing the I/O layer, and at this moment I'm wondering whether my system can safely ignore such issues (therefore blaming every possible outcome of the "undefined behavior" - including instant crash of the whole device - on the user's code) or maybe I should internally handle that somehow (for example by reference counting and actually closing the file only after the last call that uses it returns)?