linux - writing STDIN of bash application from c program -
i open bash application(prog1) , send command application c program. tried , wrote next code.
#include <stdlib.h> #include <stdio.h> #include <unistd.h> int main() { file * fp; char message[10] = "command1\n"; fp = popen("sudo prog1","r"); write(stdin_fileno, message, 10); pclose(fp); execlp("sudo prog1", "sudo prog1", "-l", null); homecoming 0; } this code gives output:
linux:~$ ./ prog 2 // running code command // prints "command" prog1-> // opens "prog1" (prog1 waits user commands) but want be
linux:~$ ./ prog 2 // running code prog1-> command // open "prog1" , write command (instead of getting user) it either writes after quitting prog1 or before starting prog1. please allow me know how write "command" in prog1, after opening application prog1. give thanks you.
note: if create
fp = popen("sudo prog1","w"); //to write it throws next error tcgetattr : inappropriate ioctl device
your main bug thinking popen() somehow associates kid process stdin_fileno. doesn't. stdin_fileno not associated "sudo prog1" child. you'd have create pipe, dup descriptors stdin/stdout, , fork+exec that. used popen() don't either.
instead, should writing , reading fp.
something like:
fprintf(fp, message); fgets(response, 100, fp); since fprintf() buffered, should utilize \n @ end of line, or fflush().
also, there no point using exec/execlp @ end when you've called popen(). looks may mixing 2 approaches you've seen example.
popen() combination of (pipe, dup stdin/stdout/stderr, fork, execl) take care of redirecting kid process file stream connected parent. no need reimplement unless need different semantics popen().
you technically implementing "expect" functionality, might want expect, or expect modules different languages. expect included linux distributions optional.
http://expect.sourceforge.net/
http://search.cpan.org/~rgiersig/expect-1.21/expect.pod
and not mention, perl has sudo module already.
http://search.cpan.org/~landman/sudo-0.21/lib/sudo.pm
c linux bash stdin
No comments:
Post a Comment