www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 8719] New: spawnvp() (POSIX) throws exception in fork()ed child process


           Summary: spawnvp() (POSIX) throws exception in fork()ed child
           Product: D
           Version: D2
          Platform: All
        OS/Version: Linux
            Status: NEW
          Severity: normal
          Priority: P2
         Component: Phobos
        AssignedTo: nobody puremagic.com
        ReportedBy: greg gerg.ca

--- Comment #0 from Greg Ward <greg gerg.ca> 2012-09-24 09:23:06 PDT ---
On POSIX systems, std.process.spawnvp() exposes its implementation to the
caller in an unexpected way: if the call to std.c.process.execvp() fails, it
throws an exception *in the forked child process*. Sample program:

import std.stdio;
import std.process;

int main() {
    string[] command = ["nosuchcommand"];
    int status;
    writefln("[pid %d]: spawning %s", getpid(), command);
    try {
        status = spawnvp(P_WAIT, command[0], command);
    catch (Exception err) {
        stderr.writefln("[pid %d] %s failed: %s",
                        getpid(), command[0], err.msg);
        return -1;
    writefln("[pid %d] %s exited with status %d",
             getpid(), command[0], status);
    return status;

Running it produces this output:

[pid 8923] spawning ["nosuchcommand"]
[pid 8924] nosuchcommand failed: Cannot spawn nosuchcommand; No such file or
directory [errno 2]
[pid 8923] nosuchcommand exited with status 255

The unexpected surprise is that *both* of my post-spawnvp() writefln() calls
happen. I expected the writefln() in the catch block to be called, but not the
one outside the catch block. The explanation is obvious once you add the PID.

The workaround is fairly easy: catch Exception and turn it into "return -1" (or
whatever you please). However, this is probably *not* the right thing to do on
Windows, where there is no fork() call. Basically the problem is that the POSIX
implementation of spawnvp() leaks an implementation detail: the use of fork().

Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Sep 24 2012