sheredom / subprocess.h

🐜 single header process launching solution for C and C++
The Unlicense
1.1k stars 97 forks source link

Commands that need to be run as root/sudo fail silently #70

Open JonathanBouligny opened 1 year ago

JonathanBouligny commented 1 year ago

This may be a command specific problem but commands that need to be run as root fail silently.

Example:

int subprocess_join_wrapper(struct subprocess_s & subproc) {
    int process_return;
    int result = subprocess_join(&subproc, &process_return);

    std::cout << "STDOUT" << std::endl;
    FILE* p_stdout = subprocess_stdout(&subproc);
    char command_output[32];
    fgets(command_output, 32, p_stdout);
    std::cout << "\n";

    if (0 != result) {
        std::cout << "STDERR" << std::endl;

        FILE* p_stderr = subprocess_stderr(&subproc);
        fgets(command_output, 32, p_stderr);
        std::cout << "\n";
    }

    return result;
}

void run_command(const char *command[], struct subprocess_s & subprocess ) {
    std::cout << "Running Command: ";
    print_command(command);
    std::cout << "Process Created: " << subprocess_create(command, 0, &subprocess) << std::endl;
    int join_result = subprocess_join_wrapper(subprocess);
    std::cout << "Process Joined: " << join_result << std::endl;
}

void LinkAdd(std::string linkName) {
    struct subprocess_s subprocess{};
   const char *deviceCreation[] = {"/bin/ip", "link", "add", "dev", linkName, "type", "bridge", nullptr};

    std::cout << "Adding link for " << linkName << "\n";
    run_command(deviceCreation, subprocess);
    std::cout << "Finished Adding link for  " << linkName << "\n";
}

int main() {
  LinkAdd("newLink");
}

If the executable isnt run as root the output is:

Adding link for newLink
Running Command: /bin/ip link add dev newLink type bridge
Process Created: 0
STDOUT

STDERR

Process Joined: 0

While running the same command on the command line gives RTNETLINK answers: Operation not permitted

I would like to output "RTNETLINK answers: Operation not permitted" or I would like to capture a failure when a command that needs to be run as root is not run as root.