spawn.c 2.56 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * spawnvp function
 *
 * Copyright 2003 Dimitrie O. Paun
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21 22 23
 */

#include "config.h"
#include "wine/port.h"

24
#if !defined(HAVE__SPAWNVP) && (!defined(_WIN32) || defined(__CYGWIN__))
25

26
#include <errno.h>
27
#include <signal.h>
28
#include <stdlib.h>
29 30 31 32 33 34 35 36
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

37
int _spawnvp(int mode, const char *cmdname, const char *const argv[])
38
{
39
    int pid, status, wret;
40

41 42
    if (mode == _P_OVERLAY)
    {
43
        execvp(cmdname, (char **)argv);
44
        /* if we get here it failed */
45 46 47 48
#ifdef ENOTSUP
        if (errno != ENOTSUP)  /* exec fails on MacOS if the process has multiple threads */
#endif
            return -1;
49
    }
50

51 52 53
    pid = fork();
    if (pid == 0)
    {
54 55 56 57 58 59 60 61 62
        /* in child */
        if (mode == _P_DETACH)
        {
            pid = fork();
            if (pid == -1) _exit(1);
            else if (pid > 0) _exit(0);
            /* else in grandchild */
        }

63
        signal( SIGPIPE, SIG_DFL );
64
        execvp(cmdname, (char **)argv);
65 66
        _exit(1);
    }
67

68 69 70 71
    if (pid == -1)
        return -1;

    if (mode == _P_OVERLAY) exit(0);
72

73
    if (mode == _P_WAIT || mode == _P_DETACH)
74 75 76 77
    {
        while (pid != (wret = waitpid(pid, &status, 0)))
            if (wret == -1 && errno != EINTR) break;

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
        if (pid == wret && WIFEXITED(status))
        {
            if (mode == _P_WAIT)
                pid = WEXITSTATUS(status);
            else /* mode == _P_DETACH */
                if (WEXITSTATUS(status) != 0) /* child couldn't fork grandchild */
                    pid = -1;
        }
        else
        {
            if (mode == _P_WAIT)
                pid = 255; /* abnormal exit with an abort or an interrupt */
            else /* mode == _P_DETACH */
                pid = -1;
        }
93 94 95
    }

    return pid;
96
}
97 98

#endif  /* HAVE__SPAWNVP */