Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!uunet!munnari.oz.au!csc!ccadfa!usage!basser!metro!bunyip!mincom!hitech!clyde From: clyde@hitech.ht.oz (Clyde Smith-Stubbs) Newsgroups: comp.unix.questions Subject: Re: Are terminal writes atomic? Message-ID: <411@hitech.ht.oz> Date: 6 Oct 89 00:52:18 GMT References: <186@promark.UUCP> Organization: HI-TECH Software, Brisbane, QLD, Australia Lines: 66 From article <186@promark.UUCP>, by mark@promark.UUCP (Mark J. DeFilippis): > In article <1118@cs.yale.edu>, spolsky-joel@CS.YALE.EDU (Joel Spolsky) writes: >> I think this is safe. A while ago I wrote a little program that runs > > How about we take this further. The answer to this question is an > undocumented feature of write() under Unix. Several Authors note > that write() is atomic under Unix and that it is undocumented. Rubbish! Writes to terminals under Unix are not, and have never been, in any way atomic. In many cases they will be atomic, but there is nothing in the structure of the system to guarantee this. It is easy to demonstrate a situation where they are not atomic. Try the following program: (If run on e.g. the memory mapped display of a 386 PC then the writes will be atomic - but on a serial terminal, or anything that uses buffering and interrupts, they will not be). char x[25][61]; main() { char c; int i, j; if(fork()) c = 'A'; else c = '.'; for(i = 0 ; i != 25 ; i++) { for (j = 0 ; j != 60 ; j++) x[i][j] = c; x[i][j] = '\n'; } for(;;) write(1, x, sizeof(x)); } For the explanation, here is the mail I sent to Jim Stratton after his original posting: From clyde Tue Sep 26 14:32:58 1989 To: stratton@hpcupt1.HP.COM Subject: Re: Are terminal writes atomic? stratton@hpcupt1.HP.COM (Jim Stratton): > I have two processes doing simultaneous output to the same terminal using the > write system call. Assume A does a write of 10 bytes while B does a write > of 30 bytes. Can I be assured that A's and B's output will not be inter- > mixed? I understand that for pipes, they won't be mixed. How about terminals? No, you can't assume that. It depends on how much output is going to the terminal. If the terminal output queue reaches the high water mark the current process will be suspended. When the queue drops to the low water mark all processes waiting on that terminal will be woken. Which one gets to write some more output first is indeterminate. ------------------------ Clyde Smith-Stubbs HI-TECH Software, P.O. Box 103, ALDERLEY, QLD, 4051, AUSTRALIA. ACSnet: clyde@hitech.ht.oz INTERNET: clyde@hitech.ht.oz.au PHONE: +61 7 300 5011 UUCP: uunet!hitech.ht.oz.au!clyde FAX: +61 7 300 5246 -- Clyde Smith-Stubbs HI-TECH Software, P.O. Box 103, ALDERLEY, QLD, 4051, AUSTRALIA. INTERNET: clyde@hitech.ht.oz.au PHONE: +61 7 300 5011 UUCP: uunet!hitech.ht.oz.au!clyde FAX: +61 7 300 5246