#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <spawn.h>
#include <cstring>
#include <string>
#include "process.h"
extern char** environ; // idk what this does
std::string spawn(char* const argv[], const char* path)
{
    pid_t pid;
    int status;
    status = posix_spawn(&pid, path, NULL, NULL, const_cast<char* const*>(argv), environ);
    if (status != 0) {
        std::cerr << "posix_spawn failed:" << strerror(status) << std::endl;
        return "error";
    }
    if (waitpid(pid, &status, 0) == -1) {
        perror("waitpid");
        return "error";
    }
    if (WIFEXITED(status)) {
        return std::to_string(WEXITSTATUS(status));
    }
    if (WIFSIGNALED(status)) {
        return std::to_string(WTERMSIG(status));
    }
    return "success";
}
