Skip to content

Instantly share code, notes, and snippets.

@geminiwen
Created May 5, 2013 15:22
Show Gist options
  • Save geminiwen/5521101 to your computer and use it in GitHub Desktop.
Save geminiwen/5521101 to your computer and use it in GitHub Desktop.
Linux 伪终端demo
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define BUFSIZE 1024
int main()
{
int ptm,sfd;
char *slavedevice;
if((ptm = open("/dev/ptmx", O_RDWR)) == -1)
{
perror("posix_openpt() error");
exit(-1);
}
fcntl(ptm, F_SETFD, FD_CLOEXEC);
if(grantpt(ptm) == -1)
{
perror("grantpt() error");
exit(-1);
}
if(unlockpt(ptm) == -1)
{
perror("unlockpt() error");
exit(-1);
}
if((slavedevice=ptsname(ptm)) == NULL)
{
perror("ptsname() error");
exit(-1);
}
int pid = fork();
if( pid == 0 ) {
close(ptm);
setsid();
int pts = open(slavedevice, O_RDWR);
if(pts < 0) exit(-1);
dup2(pts, 0);
dup2(pts, 1);
dup2(pts, 2);
execv("/bin/sh",NULL);
exit(0);
}
int nread;
char buf[BUFSIZE];
if( fork() == 0 ){
for(;;)
{
if( (nread=read(STDIN_FILENO,buf,BUFSIZE)) < 0 ){
perror("read");
break;
}
else if( nread == 0 )
break;
if( write(ptm,buf,nread) != nread ){
perror("write");
break;
}
}
} else {
for(;;)
{
if( (nread = read(ptm,buf,BUFSIZE) ) <0 )
break;
if( write (STDOUT_FILENO,buf,nread) != nread ){
perror("write");
break;
}
}
}
close(ptm);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment