popen.cpp 5.05 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Author: Zhangyi Chen (chenzhangyi01@baidu.com)
// Date: 2017/11/04 17:37:43

18
#include <gflags/gflags.h>
19 20 21 22 23 24 25 26 27 28 29 30 31
#include "butil/build_config.h"
#include "butil/logging.h"

#if defined(OS_LINUX)
// clone is a linux specific syscall
#include <sched.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

extern "C" {
uint64_t BAIDU_WEAK bthread_usleep(uint64_t microseconds);
}
gejun's avatar
gejun committed
32
#endif
33 34 35

namespace butil {

gejun's avatar
gejun committed
36 37
#if defined(OS_LINUX)

38
const int CHILD_STACK_SIZE = 256 * 1024;
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

struct ChildArgs {
    const char* cmd;
    int pipe_fd0;
    int pipe_fd1;
};

int launch_child_process(void* args) {
    ChildArgs* cargs = (ChildArgs*)args;
    dup2(cargs->pipe_fd1, STDOUT_FILENO);
    close(cargs->pipe_fd0);
    close(cargs->pipe_fd1);
    execl("/bin/sh", "sh", "-c", cargs->cmd, NULL);
    _exit(1);
}

55
int read_command_output_through_clone(std::ostream& os, const char* cmd) {
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    int pipe_fd[2];
    if (pipe(pipe_fd) != 0) {
        PLOG(ERROR) << "Fail to pipe";
        return -1;
    }
    int saved_errno = 0;
    int wstatus = 0;
    pid_t cpid;
    int rc = 0;
    ChildArgs args = { cmd, pipe_fd[0], pipe_fd[1] };
    char buffer[1024];

    char* child_stack = NULL;
    char* child_stack_mem = (char*)malloc(CHILD_STACK_SIZE);
    if (!child_stack_mem) {
        LOG(ERROR) << "Fail to alloc stack for the child process";
        rc = -1;
        goto END;
    }
    child_stack = child_stack_mem + CHILD_STACK_SIZE;  
                               // ^ Assume stack grows downward
    cpid = clone(launch_child_process, child_stack,
78
                 __WCLONE | CLONE_VM | SIGCHLD | CLONE_UNTRACED, &args);
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    if (cpid < 0) {
        PLOG(ERROR) << "Fail to clone child process";
        rc = -1;
        goto END;
    }
    close(pipe_fd[1]);
    pipe_fd[1] = -1;

    for (;;) {
        const ssize_t nr = read(pipe_fd[0], buffer, sizeof(buffer));
        if (nr > 0) {
            os.write(buffer, nr);
            continue;
        } else if (nr == 0) {
            break;
        } else if (errno != EINTR) {
            LOG(ERROR) << "Encountered error while reading for the pipe";
            break;
        }
    }

    close(pipe_fd[0]);
    pipe_fd[0] = -1;

    for (;;) {
104
        pid_t wpid = waitpid(cpid, &wstatus, WNOHANG | __WALL);
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        if (wpid > 0) {
            break;
        }
        if (wpid == 0) {
            if (bthread_usleep != NULL) {
                bthread_usleep(1000);
            } else {
                usleep(1000);
            }
            continue;
        }
        rc = -1;
        goto END;
    }

    if (WIFEXITED(wstatus)) {
        rc = WEXITSTATUS(wstatus);
        goto END;
    }

    if (WIFSIGNALED(wstatus)) {
        os << "Child process(" << cpid << ") was killed by signal "
           << WTERMSIG(wstatus);
    }

    rc = -1;
    errno = ECHILD;

END:
    saved_errno = errno;
    if (child_stack_mem) {
        free(child_stack_mem);
    }
    if (pipe_fd[0] >= 0) {
        close(pipe_fd[0]);
    }
    if (pipe_fd[1] >= 0) {
        close(pipe_fd[1]);
    }
    errno = saved_errno;
    return rc;
}

148 149 150
DEFINE_bool(run_command_through_clone, false,
            "(Linux specific) Run command with clone syscall to "
            "avoid the costly page table duplication");
151

152
#endif // OS_LINUX
153 154 155

#include <stdio.h>

156
int read_command_output_through_popen(std::ostream& os, const char* cmd) {
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    FILE* pipe = popen(cmd, "r");
    if (pipe == NULL) {
        return -1;
    }
    char buffer[1024];
    for (;;) {
        size_t nr = fread(buffer, 1, sizeof(buffer), pipe);
        if (nr != 0) {
            os.write(buffer, nr);
        }
        if (nr != sizeof(buffer)) {
            if (feof(pipe)) {
                break;
            } else if (ferror(pipe)) {
                LOG(ERROR) << "Encountered error while reading for the pipe";
                break;
            }
            // retry;
        }
    }
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

    const int wstatus = pclose(pipe);

    if (wstatus < 0) {
        return wstatus;
    }
    if (WIFEXITED(wstatus)) {
        return WEXITSTATUS(wstatus);
    }
    if (WIFSIGNALED(wstatus)) {
        os << "Child process was killed by signal "
           << WTERMSIG(wstatus);
    }
    errno = ECHILD;
    return -1;
192 193
}

194 195 196 197 198 199 200 201 202
int read_command_output(std::ostream& os, const char* cmd) {
#if !defined(OS_LINUX)
    return read_command_output_through_popen(os, cmd);
#else
    return FLAGS_run_command_through_clone
        ? read_command_output_through_clone(os, cmd)
        : read_command_output_through_popen(os, cmd);
#endif
}
203

204
}  // namespace butil