From 32e8dbc3558a7b9ddecad50a9eb241b5e36f6c02 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Mon, 31 Aug 2015 13:51:55 +0200 Subject: Add ability for process to change child's working directory --- butl/process | 8 ++++++++ butl/process.cxx | 13 +++++++++---- butl/process.ixx | 14 ++++++++++++++ 3 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 butl/process.ixx diff --git a/butl/process b/butl/process index cf18acd..c810b58 100644 --- a/butl/process +++ b/butl/process @@ -59,6 +59,12 @@ namespace butl // process (char const* args[], process& in, int out = 1, int err = 2); + // Versions of the above constructors that allow us to change the + // current working directory of the child process. + // + process (const char* cwd, char const*[], int = 0, int = 1, int = 2); + process (const char* cwd, char const*[], process& in, int = 1, int = 2); + // Wait for the process to terminate. Return true if the process // terminated normally and with the zero exit status. Throw // process_error if anything goes wrong. @@ -85,4 +91,6 @@ namespace butl }; } +#include + #endif // BUTL_PROCESS diff --git a/butl/process.cxx b/butl/process.cxx index a456217..9025bdb 100644 --- a/butl/process.cxx +++ b/butl/process.cxx @@ -5,7 +5,7 @@ #include #ifndef _WIN32 -# include // execvp, fork, dup2, pipe, {STDIN,STDERR}_FILENO +# include // execvp, fork, dup2, pipe, chdir, *_FILENO # include // waitpid #else # ifndef WIN32_LEAN_AND_MEAN @@ -25,7 +25,7 @@ namespace butl #ifndef _WIN32 process:: - process (char const* args[], int in, int out, int err) + process (const char* cwd, char const* args[], int in, int out, int err) { int out_fd[2] = {in, 0}; int in_ofd[2] = {0, out}; @@ -74,6 +74,11 @@ namespace butl throw process_error (errno, true); } + // Change current working directory if requested. + // + if (cwd != nullptr && chdir (cwd) != 0) + throw process_error (errno, true); + if (execvp (args[0], const_cast (&args[0])) == -1) throw process_error (errno, true); } @@ -93,8 +98,8 @@ namespace butl } process:: - process (char const* args[], process& in, int out, int err) - : process (args, in.in_ofd, out, err) + process (const char* cwd, char const* args[], process& in, int out, int err) + : process (cwd, args, in.in_ofd, out, err) { assert (in.in_ofd != -1); // Should be a pipe. close (in.in_ofd); // Close it on our side. diff --git a/butl/process.ixx b/butl/process.ixx new file mode 100644 index 0000000..0506793 --- /dev/null +++ b/butl/process.ixx @@ -0,0 +1,14 @@ +// file : butl/process.ixx -*- C++ -*- +// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd +// license : MIT; see accompanying LICENSE file + +namespace butl +{ + inline process:: + process (char const* args[], int in, int out, int err) + : process (nullptr, args, in, out, err) {} + + inline process:: + process (char const* args[], process& in, int out, int err) + : process (nullptr, args, in, out, err) {} +} -- cgit v1.1