Some SUDO versions use open("/dev/tty") to ensure that the password cannot be sent this way. You could do the following to avoid this:
int ptm=open("/dev/ptmx"....);
int pid=fork();
if(!pid)
{
close(0);
close(1);
close(2);
setsid();
unlockpt(...); grantpt(...);
pts=open(ptsname...);
execl(getenv("SHELL"),"sh","-c","sudo any_command",NULL);
exit(1);
}
// now the ptm file handle is used to send data
// to the process and to receive output from the process
waitpid(...);
When all ttys are closed, setsid() is called and a new tty is opened (here the /dev/ptsn) then the new tty becomes the /dev/tty for the process. This means: sudo will read the password from the pseudo-terminal.
EDIT
I just fixed a bug in my example: open("/dev/ptmx" ...)
should be called before fork()
.