read() semantics

David Mosberger (david_mosberger@hp.com)
Wed, 21 Oct 1998 09:09:26 -0700


What is the semantics of the read() system call supposed to be if the
file descriptor that is being read gets closed by some other thread?
I'd have expected that read() returns with EINVAL. Instead, it
appears as if a blocked read() keeps the file descriptor open and the
close() isn't noticed until the read() returns.

Below is a test program (courtesy of Xavier Leroy) that exhibits the
behavior in question: the main process creates a thread (clone) that
closes fd 0 after five seconds. After creating this thread, the main
process goes ahead and attempts to read one byte from fd 0. If there
is no input on stdin, I'd have expected the program to terminate with
a return code of -1 (and errno=EINVAL), but instead, the main process
behaves as if the child hadn't executed at all. Is this the intended
behavior?

Some background: I ran into this issue while working on a
pthreads-based program that attempts to be smart with respect to
avoiding having to send signals between processes (since signals are
relatively expensive). I found that on HP-UX 10.20, the above
scenario executes as expected (hoped for). Linux 2.0.32 and 2.0.34
have unexpected behavior (read ignores the close). I haven't had a
chance to test it on any other platform yet.

--david

-- 
David Mosberger;   HP Labs;   1501 Page Mill Rd MS 1U17;   Palo Alto, CA 94304
davidm@hpl.hp.com               voice (650) 236-2575              fax 857-5100

#include <stdio.h> #include <sched.h>

char stack[4096];

int child(void * arg) { sleep (5); printf ("back from sleep, closing fd 0\n"); close (0); return 0; }

int main() { int retcode; char c;

clone(child, stack + sizeof(stack), CLONE_FILES, NULL); retcode = read(0, &c, 1); printf("read returned %d\n", retcode); return 0; }

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at http://www.tux.org/lkml/