PipeStream.st
author claus
Thu, 16 Feb 1995 03:58:55 +0100
changeset 255 2b2c5c0facab
parent 230 0300c6797890
child 269 93162487a94b
permissions -rw-r--r--
*** empty log message ***

"
 COPYRIGHT (c) 1989 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"

UnboundedExternalStream subclass:#PipeStream
       instanceVariableNames:'commandString'
       classVariableNames:'BrokenPipeSignal'
       poolDictionaries:''
       category:'Streams-External'
!

PipeStream comment:'
COPYRIGHT (c) 1989 by Claus Gittinger
	      All Rights Reserved

$Header: /cvs/stx/stx/libbasic/PipeStream.st,v 1.18 1995-02-16 02:58:24 claus Exp $
'!

!PipeStream class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1989 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
!

version
"
$Header: /cvs/stx/stx/libbasic/PipeStream.st,v 1.18 1995-02-16 02:58:24 claus Exp $
"
!

documentation
"
    Pipestreams allow reading or writing from/to a unix command.
    For example, to get a stream reading the output of an 'ls -l'
    command, a PipeStream can be created with:

	PipeStream readingFrom:'ls -l'

    the characters of the commands output can be read using the
    standard stream messages as next, nextLine etc.

    If a writing pipeStream is written to, after the command has finished,
    UNIX will generate an error-signal (SIGPIPE), which will raise the
    BrokenPipeSignal. 
    Thus, to handle this condition correctly, the following code is suggested:

	|p|
	p := PipeStream writingTo:'echo hello'.
	PipeStream brokenPipeSignal handle:[:ex |
	    'broken pipe' printNewline.
	    p shutDown.
	    ex return
	] do:[
	    p nextPutLine:'oops'.
	   'after write' printNewline.
	    p close.
	   'after close' printNewline
	]

    Notice, that if the Stream is buffered, the Signal may occur some time after
    the write - or even at close time; to avoid a recursive signal in the exception
    handler, a shutDown is useful there.
"
! !

!PipeStream primitiveDefinitions!

%{
#include <stdio.h>
#include <errno.h>
#ifndef transputer
# include <sys/types.h>
# include <sys/stat.h>
#endif

extern int __immediateInterrupt__;
/*
 * on some systems errno is a macro ... check for it here
 */
#ifndef errno
 extern errno;
#endif

%}
! !

!PipeStream class methodsFor:'initialization'!

initialize
    "setup the signal"

    BrokenPipeSignal isNil ifTrue:[
	Object initialize.

	BrokenPipeSignal := Object errorSignal newSignalMayProceed:true.
	BrokenPipeSignal nameClass:self message:#brokenPipeSignal.
	BrokenPipeSignal notifierString:'write on a pipe with no one to read'.
    ]
! !

!PipeStream class methodsFor:'signal access'!

brokenPipeSignal
    "return the signal used to handle SIGPIPE unix-signals"

    ^ BrokenPipeSignal
! !

!PipeStream class methodsFor:'instance creation'!

writingTo:commandString
    "create and return a new pipeStream which can write to the unix command
     given by command."

    ^ (self basicNew) writingTo:commandString

    "PipeStream writingTo:'sort'"
!

readingFrom:commandString
    "create and return a new pipeStream which can read from the unix command
     given by command."

    ^ (self basicNew) readingFrom:commandString

    "PipeStream readingFrom:'ls -l'"
! !

!PipeStream methodsFor:'accessing'!

commandString
    "return the command string"

    ^ commandString
! !

!PipeStream methodsFor:'instance release'!

disposed
    "redefined to avoid blocking in close."

    self shutDown
!

shutDown
    "close the Stream, ignoring any broken-pipe errors"

    BrokenPipeSignal catch:[self closeFileDescriptor]
!

closeFile
    "low level close - redefined since we close a pipe here.
     This waits for the command to finish. 
     Use shutDown for a fast (nonBlocking) close."

%{  /* UNLIMITEDSTACK */
#ifndef transputer

    if (_INST(filePointer) != nil) {
	/*
	 * allow interrupt even when blocking here ...
	 */
	__immediateInterrupt__ = 1;
	pclose(MKFD(_INST(filePointer)));
	__immediateInterrupt__ = 0;
	_INST(filePointer) = nil;
    }
#endif
%}
! !

!PipeStream methodsFor:'private'!

XXatEnd
    "return true, if position is at end"

%{  /* NOCONTEXT */
#ifdef IRIX5
    FILE *f;
    OBJ t;
    OBJ _true = true;
    int c;

    if (_INST(hitEOF) == _true) {
	RETURN (_true);
    }
    if ((t = _INST(filePointer)) != nil) {
	f = MKFD(t);
	if (feof(f)) {
	    _INST(hitEOF) = true;
	    RETURN (true);
	}
	RETURN ( false );
    }
#endif
%}
.
    ^ super atEnd
! !

!PipeStream methodsFor:'private'!

openPipeFor:aCommandString withMode:mode
    "open a pipe to the unix command in aCcommandString; 
     mode may be 'r' or 'w'"

    |retVal|

    filePointer notNil ifTrue:[^ self errorOpen].

%{  /* STACK: 32000 */
#ifndef transputer
    FILE *f;

    _INST(lastErrorNumber) = nil;

    if (__isString(aCommandString) && __isString(mode)) {
	__immediateInterrupt__ = 1;
	do {
#ifdef LINUX
	    /* LINUX returns a non-NULL f even when interrupted */
	    errno = 0;
	    f = (FILE *)popen((char *) _stringVal(aCommandString),
			      (char *) _stringVal(mode));
	    if (errno == EINTR)
		f = NULL;
#else
	    f = (FILE *)popen((char *) _stringVal(aCommandString),
			      (char *) _stringVal(mode));
#endif
	} while ((f == NULL) && (errno == EINTR));
	__immediateInterrupt__ = 0;
	if (f == NULL) {
	    _INST(lastErrorNumber) = _MKSMALLINT(errno);
	} else {
	    _INST(filePointer) = MKOBJ(f);
	    retVal = self;
	}
    }
#endif
%}.
    retVal notNil ifTrue:[
	commandString := aCommandString.
	buffered := true.
	hitEOF := false.
	Lobby register:self
    ].
    lastErrorNumber notNil ifTrue:[
	"
	 the open failed for some reason ...
	"
	^ self openError
    ].
    ^ retVal
!

readingFrom:command
    "setup the receiver to read from command"

    self readonly. didWrite := false.
    ^ self openPipeFor:command withMode:'r'
!

writingTo:command
    "setup the receiver to write to command"

    self writeonly. didWrite := true.
    ^ self openPipeFor:command withMode:'w'
! !