]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- |
2 | // vim: ts=8 sw=2 smarttab | |
3 | /* | |
4 | * Ceph - scalable distributed file system | |
5 | * | |
6 | * Copyright (C) 2011 New Dream Network | |
7 | * | |
8 | * This is free software; you can redistribute it and/or | |
9 | * modify it under the terms of the GNU Lesser General Public | |
10 | * License version 2.1, as published by the Free Software | |
11 | * Foundation. See file COPYING. | |
12 | * | |
13 | */ | |
14 | ||
15 | #include "common/errno.h" | |
16 | ||
17 | #include <errno.h> | |
18 | #include <sstream> | |
19 | #include <stdarg.h> | |
20 | #include <stdlib.h> | |
21 | #include <sys/wait.h> | |
22 | #include <unistd.h> | |
23 | #include <vector> | |
24 | ||
25 | using std::ostringstream; | |
26 | ||
27 | std::string run_cmd(const char *cmd, ...) | |
28 | { | |
29 | std::vector <const char *> arr; | |
30 | va_list ap; | |
31 | va_start(ap, cmd); | |
32 | const char *c = cmd; | |
33 | do { | |
34 | arr.push_back(c); | |
35 | c = va_arg(ap, const char*); | |
36 | } while (c != NULL); | |
37 | va_end(ap); | |
38 | arr.push_back(NULL); | |
39 | ||
40 | int fret = fork(); | |
41 | if (fret == -1) { | |
42 | int err = errno; | |
43 | ostringstream oss; | |
44 | oss << "run_cmd(" << cmd << "): unable to fork(): " << cpp_strerror(err); | |
45 | return oss.str(); | |
46 | } | |
47 | else if (fret == 0) { | |
48 | // execvp doesn't modify its arguments, so the const-cast here is safe. | |
49 | close(STDIN_FILENO); | |
50 | close(STDOUT_FILENO); | |
51 | close(STDERR_FILENO); | |
52 | execvp(cmd, (char * const*)&arr[0]); | |
53 | _exit(127); | |
54 | } | |
55 | int status; | |
56 | while (waitpid(fret, &status, 0) == -1) { | |
57 | int err = errno; | |
58 | if (err == EINTR) | |
59 | continue; | |
60 | ostringstream oss; | |
61 | oss << "run_cmd(" << cmd << "): waitpid error: " | |
62 | << cpp_strerror(err); | |
63 | return oss.str(); | |
64 | } | |
65 | if (WIFEXITED(status)) { | |
66 | int wexitstatus = WEXITSTATUS(status); | |
67 | if (wexitstatus != 0) { | |
68 | ostringstream oss; | |
69 | oss << "run_cmd(" << cmd << "): exited with status " << wexitstatus; | |
70 | return oss.str(); | |
71 | } | |
72 | return ""; | |
73 | } | |
74 | else if (WIFSIGNALED(status)) { | |
75 | ostringstream oss; | |
76 | oss << "run_cmd(" << cmd << "): terminated by signal"; | |
77 | return oss.str(); | |
78 | } | |
79 | ostringstream oss; | |
80 | oss << "run_cmd(" << cmd << "): terminated by unknown mechanism"; | |
81 | return oss.str(); | |
82 | } |