Commit abbfd20b by Daniel Lezcano Committed by Daniel Lezcano

use popen and redirect script output

Change the run_script function to use popen and to redirect the output of the script to the log file. Signed-off-by: 's avatarDaniel Lezcano <dlezcano@fr.ibm.com>
parent 751d9dcd
...@@ -189,54 +189,57 @@ static struct caps_opt caps_opt[] = { ...@@ -189,54 +189,57 @@ static struct caps_opt caps_opt[] = {
static int run_script(const char *name, const char *section, static int run_script(const char *name, const char *section,
const char *script, ...) const char *script, ...)
{ {
va_list argp; int ret;
int vargc = 4; FILE *f;
int status = 0; char *buffer, *p, *output;
size_t size = 0;
/* count variable arguments and add 4 for script, container va_list ap;
* and section name as well as the terminating NULL
*/
va_start(argp, script);
while (va_arg(argp, char*)) vargc++;
va_end(argp);
INFO("Executing script '%s' for container '%s', config section '%s'", INFO("Executing script '%s' for container '%s', config section '%s'",
script, name, section); script, name, section);
int pid = fork();
if (pid < 0) { va_start(ap, script);
ERROR("Error forking"); while ((p = va_arg(ap, char *)))
size += strlen(p);
va_end(ap);
size += strlen(script);
size += strlen(name);
size += strlen(section);
buffer = alloca(size + 1);
if (!buffer) {
ERROR("failed to allocate memory");
return -1; return -1;
} }
if (pid == 0) { ret = sprintf(buffer, "%s %s %s", script, name, section);
/* prepare command line arguments */ va_start(ap, script);
char *args[vargc]; while ((p = va_arg(ap, char *)))
int i; ret += sprintf(buffer + ret, " %s", p);
args[0] = strdup(script); va_end(ap);
args[1] = strdup(name);
args[2] = strdup(section);
va_start(argp, script); f = popen(buffer, "r");
for (i = 3; i < vargc; i++) if (!f) {
args[i] = va_arg(argp, char*); SYSERROR("popen failed");
va_end(argp); return -1;
}
args[vargc-1] = (char*) NULL;
execv(script, args); output = malloc(LXC_LOG_BUFFER_SIZE);
/* if we cannot exec, we exit this fork */ if (!output) {
SYSERROR("Failed to execute script '%s' for container '%s': %s", ERROR("failed to allocate memory for script output");
script, name); return -1;
exit(1);
} }
waitpid(pid, &status, 0); while(fgets(output, LXC_LOG_BUFFER_SIZE, f))
if (status != 0) { DEBUG("script output: %s", output);
/* something weird happened */
SYSERROR("Script '%s' terminated with non-zero exitcode %d", free(output);
name, status);
if (pclose(f)) {
ERROR("Script exited on error");
return -1; return -1;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment