Skip to content
Back to formatted view

Raw Message

Message-ID: <Pine.LNX.4.44.0305301613300.5956-100000@gannet.stats>
Date: 2003-05-30T15:28:53Z
From: Brian Ripley
Subject: How to check if a pipe was successfully opened or not?
In-Reply-To: <000501c326b9$67413dc0$e502eb82@alpha.wehi.edu.au>

On Fri, 30 May 2003, Henrik Bengtsson wrote:

> Is there a way to detect if the opening of a connection to a pipe was
> successful or not? Here are two examples
> 
>  # Works
>  > con <- pipe("ls")
>  > res <- open(con, open="r")
>  > print(res)
>  NULL
> 
>  # Does not work
>  > con <- pipe("unknown_command")
>  > res <- open(con, open="r")
>  > 'unknown_command' is not recognized as an internal or external
> command,
>  operable program or batch file.
>  > print(res)
>  NULL

open() always returns NULL.

> Can I make my script recognize/detect that the latter failed? try() will
> not catch the error. The error message is not written to stdout so
> sink() won't "catch" it either. Does anyone know of a (cross-platform)
> way to test if "unknown_command" exists or not on the current system
> before calling pipe()/open()? 
> 
> I'm running R v1.7.0 on WinXP.

The C code called by open() has

    fp = popen(con->description, mode);
    if(!fp) {
	warning("cannot open cmd `%s'", con->description);
	return FALSE;
    }

so presumably your system's popen is returning a FILE stream even though 
the command cannot be opened.  Not much we can do about that.  Solaris 
says

    The popen() function returns a null pointer if files or
    processes cannot be created.

but I think the problem is that the `process' is that launching the shell, 
not that of the command.  I am not using Windows, so cannot check there.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595