Sending data to a command using C
For example, when you enter su at the terminal, you get a prompt that asks you for the password. I want to know how to 'write' the password to that prompt and 'press' enter.
I know that system("su") will start the su command and give you the prompt, but how do I actually 'type' the password using a program? |
you want popen(char*, char*). Actually, one or both of those char*'s may be const. Anyhow, it opens a pipe to the given process, and works like fopen. It would be called like so
Code:
FILE* pipe = popen("su", "w") |
Quote:
How does su distinguish b/w me and the program? Does it check if the input is from stdin? |
you can still run it from a program by using a pseudo-terminal (pty), but I don't think this is what you want. Correct me if I'm wrong, but it seems that you want to enter a password in your program that would give you the privileges of another user? By running su in a pty, you could try to run other commands as root, but not gain root status for your own program.
|
Code:
foo@foo:/mnt/D/Programs/C$ touch a.g b.g c.g d.g e.g f.g EDIT: I simply want to learn more C. I'm not putting this in any other program.. just curious! |
hrm... beats me
|
I think you've basically implemented the following
echo "y"|rm *.g which works, as in deletes all *.g files (although in bash I do get a 'bash: echo: write error: Broken pipe' error after it's finished.) |
No, it doesn't. It only deletes the first file as expected. To the others, it sends the Enter key( I think, because normally after entering 'y', you are required to press Enter. Since I sent only one 'y', it 'pressed' enter till the command was completed) I'm using bash.
Code:
foo@foo:~$ touch a.g b.g c.g d.g |
Anyone knows why this happens?
|
Please tell me, I've waited for a very long time. Is it something very small?
|
My guess is the pclose(). Since the command exists only on the other end of that pipe, it is terminated after the first 'y' is sent. Thus, only the first file is removed. Regarding the
Code:
echo "y" | rm *.g Code:
rm -f *.g |
Ooops, I've misunderstood the question. All of them were deleted, but only the first should have been. I still suspect the pclose though. It is generally not a good idea to close the pipe to such a program before it terminates, as you can get undefined results, like this. In fact, if you moved to a system with, for instance, the busybox rm the result may be different.
|
Ok, is there an alternative way to code this?
P.S. It's rm -i that is to be used, not rm. Only rm will not give any confirmation, and will delete every file. |
I figured it out. I forgot to simulate the Enter key.
Code:
foo@foo:~/Programs/C$ touch a.g b.g c.g |
It's the -i switch effect that I was dealing with as per gregorian's last comment.
The same technique can be used with other cmds that prompt for confirmation (install scripts for eg). |
All times are GMT -5. The time now is 06:57 PM. |