src/process.cpp

changeset 4
82680ce258d6
parent 2
7384ebae6b7c
child 18
fd7a7785c963
--- a/src/process.cpp	Tue Jan 21 20:24:45 2025 +0100
+++ b/src/process.cpp	Tue Jan 21 21:01:54 2025 +0100
@@ -32,16 +32,23 @@
 
 using namespace fm;
 
-process::process(std::string path): m_path(std::move(path)) {
+void process::setbin(std::string path) {
+    m_path = std::move(path);
 }
 
-bool process::exec(std::vector<std::string> args) {
+void process::chdir(std::string path) {
+    m_dir = std::move(path);
+}
+
+int process::exec(std::vector<std::string> args, bool capture) {
+    m_output.clear();
+
     // fd-pair for the pipe
     int pipefd[2];
 
     if (pipe(pipefd)) {
         perror("pipe");
-        return false;
+        return -1;
     }
 
     pid_t pid = fork();
@@ -68,34 +75,40 @@
         argv[args.size() + 1] = nullptr;
 
         // execute the child program
+        if (::chdir(m_dir.c_str())) {
+            perror("chdir");
+            exit(EXIT_FAILURE);
+        }
         if (execv(m_path.c_str(), argv)) {
             perror("execl");
             exit(EXIT_FAILURE);
         }
-        return true; // unreachable, but the compiler doesn't know that
+        return 0; // unreachable, but the compiler doesn't know that
     } else if (pid > 0) {
         // close the end of the pipe we don't use
         close(pipefd[1]);
 
         // read all the output
-        char buf[64];
-        ssize_t r;
-        while ((r = read(pipefd[0], buf, sizeof(buf))) > 0) {
-            m_output.append(buf, r);
+        if (capture) {
+            char buf[64];
+            ssize_t r;
+            while ((r = read(pipefd[0], buf, sizeof(buf))) > 0) {
+                m_output.append(buf, r);
+            }
+            if (r < 0) {
+                perror("read");
+            }
+            close(pipefd[0]);
         }
-        if (r < 0) {
-            perror("read");
-        }
-        close(pipefd[0]);
 
         // wait for the process to completely finish
         int status = -1;
         waitpid(pid, &status, 0);
 
-        return status == 0;
+        return status;
     } else {
         perror("fork");
-        return false;
+        return -1;
     }
 }
 

mercurial