All pastes #259167 Raw Edit

bytenik

public cpp v1 · immutable
#259167 ·published 2006-11-27 04:30 UTC
rendered paste body
#include <iostream>#include <cstdlib>#include <string>#include <fstream>#include <ext/stdio_filebuf.h>#include <sys/types.h>#include <sys/time.h>#include <sys/wait.h>#include <unistd.h>#include <pty.h>#include <errno.h>using namespace std;int main(int argc, char *argv[]){	if(argc != 2)	{		cerr << "Usage: " << argv[0] << " [filename]" << endl;		return 1;	}	// open the pty, storing file descriptors in amaster and aslave	int amaster, aslave;	if(openpty(&amaster, &aslave, NULL, NULL, NULL) < 0)	{		perror("openpty");		return errno;	}	ios::sync_with_stdio(true);	pid_t process = fork();	if(process < 0)	{		perror("fork");		return errno;	}	else if(process > 0)	{		if(close(aslave) < 0)			perror("close aslave");		ofstream output(argv[1]);		__gnu_cxx::stdio_filebuf<char> buf(amaster, ios_base::in | ios_base::out, 1);		iostream master(&buf);		fd_set readfds, emptyfds1, emptyfds2;		FD_ZERO(&emptyfds1);		FD_ZERO(&emptyfds2);				while(true)		{cerr << "0";			FD_ZERO(&readfds);						FD_SET(amaster, &readfds);			FD_SET(0, &readfds);					if(select(amaster + 1, &readfds, &emptyfds1, &emptyfds2, NULL) < 0)			{				perror("select");				//return errno;			}cerr << "1" << endl;			if(FD_ISSET(0, &readfds))			{				char indata;				cin.get(indata);				master << indata;			}cerr << "2" << endl;			if(FD_ISSET(amaster, &readfds))			{				char indata;				cin.get(indata);				cout << indata;			}cerr << "3" << endl;		}		output.close();	}	else	{		if(close(amaster) < 0)			perror("close amaster");		if(dup2(aslave, 0) < 0) // makes stdin			perror("dup2 aslave, 0");		if(dup2(aslave, 1) < 0) // makes stdout			perror("dup2 aslave, 1");		if(dup2(aslave, 2) < 0) // makes stderr			perror("dup2 aslave, 2");		char *shellc = getenv("SHELL");		string shell;		if(shellc != NULL)			shell = shellc;		else			shell = "/bin/sh";		cerr << shell;		if(execl(shell.c_str(), shell.c_str(), NULL) < 0)		{			perror("execl");			return errno;		}		cerr << "shell end";	}}