 /****************************************************************************\
| create a tty using Xterm and output its name and pid on stdout.              |
| usage: mkxtty [xterm-args]                                                   |
| (c) 1994 by HighTec EDV-Systeme GmbH, 05/13/94 (ms)                          |
 \****************************************************************************/

#include <stdio.h>
#include <sys/signal.h>
#define XTERM_PROG "xterm"	/* may also be "rxvt" or "xterm-color"... */

void main(int argc, char *argv[])
{
  int pid, ipipe[2];
  char buffer[100];
  extern char *getenv();


  if ((argc == 4) && !strcmp(argv[1], "-c"))
  { sscanf(getenv("WINDOWID"), "%i", &pid);
    ipipe[0] = atoi(argv[2]); ipipe[1] = atoi(argv[3]);
    sprintf(buffer, "%d %s %d", pid, ttyname(0), getpid());
    write(ipipe[1], buffer, strlen(buffer));
    signal(SIGINT,  SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGTSTP, SIG_IGN);
    setpgid(0, 0);
    close(ipipe[0]); close(ipipe[1]); close(0); close(1);
    while (1)
      sleep(3600);
  }

  pipe(ipipe);
  if ((pid = fork()) == -1)
  { fprintf(stderr, "%s: can't fork()\n", argv[0]);
    exit(1);
  }
  if (pid == 0)
  { char **xargv = (char **)malloc((argc+6) * sizeof(char *));
    char p0desc[5], p1desc[5];
    int xargc;

    if (xargv == NULL)
    { fprintf(stderr, "%s: can't malloc()\n", argv[0]);
      exit(1);
    }
    sprintf(p0desc, "%d", ipipe[0]); sprintf(p1desc, "%d", ipipe[1]);
    xargv[0] = XTERM_PROG;
    for (xargc = 1; xargc < argc; ++xargc)
      xargv[xargc] = argv[xargc];
    xargv[xargc++] = "-e";
    xargv[xargc++] = argv[0];
    xargv[xargc++] = "-c";
    xargv[xargc++] = p0desc;
    xargv[xargc++] = p1desc;
    xargv[xargc] = NULL;
    execvp(xargv[0], xargv);
    fprintf(stderr, "%s: can't exec()\n", argv[0]);
    exit(1);
  }

  read(ipipe[0], buffer, 100); printf("%s\n", buffer);
  exit(0);
}
