/* switchtty.c
 *   Switch current TTY to another.
 *   Usage: ./switchtty ttynr
 *
 * Copyright (c) 2005, Sven Bachmann
 * All rights reserved.
 *
 * License: BSD
 */

#include <stdio.h>
#include <fcntl.h>
#ifdef __FreeBSD__
#include <sys/consio.h>
#else
#include <linux/vt.h>
#endif
#include <errno.h>

int main(int argc, char * argv[])
{
    int fd;
    int res;
    unsigned long tty;

    if (argc < 2) {
	fprintf(stderr, "switchtty: No tty given.\n");
	return 1;
    }

    if (sscanf(argv[1], "%ld", &tty) < 0) {
	fprintf(stderr, "switchtty: Wrong argument.\n");
	return 1;
    }

    if (tty < 1) {
	fprintf(stderr, "switchtty: TTY less than 1.\n");
	return 1;
    }

    fd = open("/dev/console", O_RDONLY);
    if (fd < 0) {
	fprintf(stderr, "switchtty: Could not open /dev/console.\n");
	return 1;
    }

    res = ioctl(fd, VT_ACTIVATE, tty);
    if (res < 0) {
	fprintf(stderr, "switchtty: ioctl failed.\n");
	close(fd);
	return 1;
    }
    close(fd);
    return 0;
}

