linux - Getting all output from terminal in C -
i working on ssh program , want able have full control on terminal via networking. question is, if send command server run in terminal, how output terminal prints? have seen many posts saying use popen()
command have tried can't change directories , other commands using this, simple things such ls
. there other way output terminal besides sending file command > filetoholdcommand
. in advance!
i put comment, dont have enough rep i'm new. cd built in shell command want use system(). cd have no effect on process (you have use chdir(), that),so want start shell subprocess via fork/exec, connect pipes stdin , stdout,then pipe commands duration of user session or connection.
following code give general idea. basic, , flawed - use select() not usleep() one.
int argc2; printf( "server started - %d\n", getpid() ); char buf[1024] = {0}; int pid; int pipe_fd_1[2]; int pipe_fd_2[2]; pipe( pipe_fd_1 ); pipe( pipe_fd_2 ); switch ( pid = fork() ) { case -1: exit(1); case 0: /* child */ close(pipe_fd_1[1]); close(pipe_fd_2[0]); dup2( pipe_fd_1[0], stdin_fileno ); dup2( pipe_fd_2[1], stdout_fileno ); execlp("/bin/bash", "bash", null); default: /* parent */ close(pipe_fd_1[0]); close(pipe_fd_2[1]); fcntl(pipe_fd_2[0], f_setfl, fcntl(pipe_fd_2[0], f_getfl, null ) | o_nonblock ); while(true) { int r = 0; printf( "enter cmd:\n" ); r = read( stdin_fileno, &buf, 1024 ); if( r > 1 ) { buf[r] = '\0'; write(pipe_fd_1[1], &buf, r); } usleep(100000); while( ( r = read( pipe_fd_2[0], &buf, 1024 ) ) > 0 ) { buf[r-1] = '\0'; printf("%s", buf ); } printf("\n"); } }
Comments
Post a Comment