0

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.

Pietro
  • 12,086
  • 26
  • 100
  • 193

2 Answers2

3

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

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.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169