os/process: add pid()

This commit is contained in:
Vaxry 2024-12-21 15:47:46 +00:00
parent e6cf45cd18
commit c3331116eb
3 changed files with 24 additions and 2 deletions

View file

@ -3,6 +3,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <utility> #include <utility>
#include <sys/types.h>
namespace Hyprutils { namespace Hyprutils {
namespace OS { namespace OS {
@ -23,10 +24,14 @@ namespace Hyprutils {
const std::string& stdOut(); const std::string& stdOut();
const std::string& stdErr(); const std::string& stdErr();
// only populated when ran async
const pid_t pid();
private: private:
std::string binary, out, err; std::string binary, out, err;
std::vector<std::string> args; std::vector<std::string> args;
std::vector<std::pair<std::string, std::string>> env; std::vector<std::pair<std::string, std::string>> env;
pid_t grandchildPid = 0;
}; };
} }
} }

View file

@ -209,7 +209,9 @@ bool Hyprutils::OS::CProcess::runAsync() {
read(socket[0], &grandchild, sizeof(grandchild)); read(socket[0], &grandchild, sizeof(grandchild));
close(socket[0]); close(socket[0]);
// clear child and leave grandchild to init // clear child and leave grandchild to init
waitpid(child, NULL, 0); waitpid(child, nullptr, 0);
grandchildPid = grandchild;
return true; return true;
} }
@ -220,4 +222,8 @@ const std::string& Hyprutils::OS::CProcess::stdOut() {
const std::string& Hyprutils::OS::CProcess::stdErr() { const std::string& Hyprutils::OS::CProcess::stdErr() {
return err; return err;
} }
const pid_t Hyprutils::OS::CProcess::pid() {
return grandchildPid;
}

View file

@ -1,3 +1,7 @@
#include <csignal>
#include <cerrno>
#include <cstdlib>
#include <unistd.h>
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include "shared.hpp" #include "shared.hpp"
@ -15,5 +19,12 @@ int main(int argc, char** argv, char** envp) {
EXPECT(process.stdOut(), std::string{"Hello World!\n"}); EXPECT(process.stdOut(), std::string{"Hello World!\n"});
EXPECT(process.stdErr(), std::string{""}); EXPECT(process.stdErr(), std::string{""});
CProcess process2("sh", {"-c", "while true; do sleep 1; done;"});
EXPECT(process2.runAsync(), true);
EXPECT(getpgid(process2.pid()) >= 0, true);
kill(process2.pid(), SIGKILL);
return ret; return ret;
} }