1 /* 2 * Copyright 2008, Ingo Weinhold, ingo_weinhold@gmx.de. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 #include <pty.h> 7 8 #include <errno.h> 9 #include <fcntl.h> 10 #include <stdlib.h> 11 #include <string.h> 12 13 14 int 15 openpty(int* _master, int* _slave, char* name, struct termios* termAttrs, 16 struct winsize* windowSize) 17 { 18 int master = posix_openpt(O_RDWR); 19 if (master < 0) 20 return -1; 21 22 int slave; 23 const char *ttyName; 24 if (grantpt(master) != 0 || unlockpt(master) != 0 25 || (ttyName = ptsname(master)) == NULL 26 || (slave = open(ttyName, O_RDWR | O_NOCTTY)) < 0) { 27 close(master); 28 return -1; 29 } 30 31 if (termAttrs != NULL && tcsetattr(master, TCSANOW, termAttrs) != 0 32 || windowSize != NULL 33 && ioctl(master, TIOCSWINSZ, windowSize, sizeof(winsize)) != 0) { 34 close(slave); 35 close(master); 36 } 37 38 *_master = master; 39 *_slave = slave; 40 41 if (name != NULL) 42 strcpy(name, ttyName); 43 44 return 0; 45 } 46