Created
February 20, 2012 19:05
-
-
Save vikraman/1870763 to your computer and use it in GitHub Desktop.
Shell on a pty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pty.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <termios.h> | |
#include <sys/select.h> | |
#define BUF_SIZE 80 | |
int main () { | |
int pty, nbytes; | |
fd_set des_set; | |
char buf[BUF_SIZE]; | |
struct termios attr; | |
pid_t pid = forkpty(&pty, NULL, NULL, NULL); | |
switch(pid) { | |
case -1: | |
perror("forkpty"); | |
exit(EXIT_FAILURE); | |
break; | |
case 0: | |
execlp("/bin/login", "/bin/login", NULL); | |
perror("exelp"); | |
exit(EXIT_FAILURE); | |
break; | |
default: | |
/* turn off echo and canonical mode */ | |
tcgetattr(STDIN_FILENO, &attr); | |
attr.c_lflag &= ~(ECHO|ICANON); | |
attr.c_cc[VTIME] = 0; | |
attr.c_cc[VMIN] = 0; | |
tcsetattr(STDIN_FILENO, TCSANOW, &attr); | |
while (1) { | |
FD_ZERO (&des_set); | |
FD_SET (pty, &des_set); | |
FD_SET (STDIN_FILENO, &des_set); | |
if (select (FD_SETSIZE, &des_set, NULL, NULL, NULL) < 0) | |
{ | |
perror ("select"); | |
exit (EXIT_FAILURE); | |
} | |
/* from stdin to pty */ | |
if (FD_ISSET (STDIN_FILENO, &des_set)) | |
{ | |
nbytes = read(STDIN_FILENO, buf, BUF_SIZE); | |
if (nbytes > 0) | |
write(pty, buf, nbytes); | |
else if (nbytes < 0) | |
exit(EXIT_FAILURE); | |
} | |
/* from pty to stdout */ | |
if (FD_ISSET (pty, &des_set)) | |
{ | |
nbytes = read(pty, buf, BUF_SIZE); | |
if (nbytes > 0) | |
write(STDOUT_FILENO, buf, nbytes); | |
else if (nbytes < 0) | |
exit(EXIT_FAILURE); | |
} | |
} | |
close(pty); | |
break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment