sudo in c?

Reznic Valery Valery_Reznic at
Mon Jun 23 07:51:36 EDT 2003

-----Original Message-----
From: Martin Klaffenboeck [mailto:martin.klaffenboeck at]
Sent: Monday, June 23, 2003 2:12 PM
To: Reznic Valery
Cc: mlh at; 'sudo-users at'
Subject: Re: sudo in c?

Am 2003.06.23 12:59 schrieb(en) Reznic Valery:

> That would be better.  In specific:  I do want to have two functions
> for sudo in my programm, or maybe more, but two main functions:
> For password validating you can use code like this:
> {
>   // Flag v will force sudo only validate password and do nothing
>   // Flag S - read password from STDIN, and not terminal device
>   char *passwd = you_have some_how initialize password (for example,
> ask
> user for it);
>    FILE *p = popen("sudo -v -S", "w");
>    fprintf(p, "%s\n", passwd);
> }

Yes I had that and it worked.  I just didn't know how I can set the 
functions return value, so that the caller of the password validateing 
function can know if it went good or not.  So now I have the opinion to 
do 2&>1 and parse the output, right?

No, you have not.
When you have popen("command", "w") you have ONLY option write to the
stdin. Both stdout or stderr unavailable. (you can redirect stdout/stderr to
the file
and read it, but it's a mess) popen("command 1>out 2>err". "w");

A way you can get information is use pclose(p);
When command will return; pclose will return too.
You can analize pclose retirn value to get exit status.
0 - password is ok, 1 - wrong one.

The only trouble with it that sudo can be confgured to the different number
of prompts
before get out.
So you have use something like
    FILE *p = popen("sudo -v -S", "w");
    while (eof_on_the_p_file_descriptor) {
       fprintf(p, "%s\n", passwd);

> Function sudo_run_command is really
> Run_Same_Command_And_Got_It_Stdout_And_Stderr.
> But output can be huge !

Yes, you are right.  Normally the output will be parsed and a copy of 
it will go to a GtkTextBuffer.

> I think a better solution is provide a program with a file descriptor
>  and let to application to decide how allocate space and when and how
> allocate data).

Hm.  Maybe I don't know enaugh about pipes?  I thought the function can 
loose the information and the callback function has to allocate and 
write the data somewhere.  In the GtkTextBuffer, gtk ist doing that for 
me, in the library which uses plain c, I'm not sure.  There I will only 
give the output back to the terminal after parsing (or parallel).
I do not understand you here


> If you reall need both stderr and stdout (or may be stdin too, you can
> have
> a look to the Nedit editor sources
> It has implementation for "improved popen".

Hm.  It's hard to read the sources for me I think, but I can try.


If you've got an idea and need help,
or just need general encouragement,
write me a message. ;-)

More information about the sudo-users mailing list