how to open /dev/console in C

I was reading wayland/weston code, the setting up tty part. I found it tries to acquire an avaliable tty for doing KMS and start windows.

This is how it does:

    if (!wl->new_user) {
            wl->tty = STDIN_FILENO;
    } else if (tty) {
            t = ttyname(STDIN_FILENO);
            if (t && strcmp(t, tty) == 0)
                    wl->tty = STDIN_FILENO;
                    wl->tty = open(tty, O_RDWR | O_NOCTTY);
    } else {
            int tty0 = open("/dev/tty0", O_WRONLY | O_CLOEXEC);
            char filename[16];

            if (tty0 < 0)
                    error(1, errno, "could not open tty0");

            if (ioctl(tty0, VT_OPENQRY, &wl->ttynr) < 0 || wl->ttynr == -1)
                    error(1, errno, "failed to find non-opened console"); 

            snprintf(filename, sizeof filename, "/dev/tty%d", wl->ttynr);
            wl->tty = open(filename, O_RDWR | O_NOCTTY);

in src/weston-launch.c.

It tries to open(‘/dev/tty0’) and find a tty that avaliable if no tty is specified.

But you can’t do that, neither ‘/dev/tty0’ nor ‘avaliable tty’ belongs to you. I tested with my simpler version.And of course I couldn’t open ‘/dev/tty0’.

Do you guys know how this magic is done? Appreciate your help 🙂

Source: c#

Leave a Reply