Q: How to use "sudo" from a C program without using system()? I have the following code:
std::string cmd = "sudo chmod a+x file";
int r = system(cmd.c_str());

which works correctly.
How can I do the same thing without calling the system() function?
What I can get to is:
#include <sys/stat.h>
int r = chmod("file", S_IXUSR | S_IXGRP | S_IXOTH);

How can I use "sudo" in this case?
Thank you.

A: You can't. Unless your program is suid root which is most likely not the case - otherwise you wouldn't use sudo.
However, depending on what your program does, giving it setuid-root might indeed be the way to go. You need to perform operations that require root privileges and sudo access to chmod, especially on arbitrary modes/paths, is usually not granted to non-root users.

A: Privileges are based on process. One way of handling this is to make your program have the setuid bit set on and owned by root. After it launches, do whatever you want to that requires privileges and then drop the privileged status using the setuid system call. 
