1

I have some code:

char *tty_name = ttyname(STDIN_FILENO);
char command[255] = "/usr/sbin/writevt -t "; strcpy(stpcpy(command + 21, tty_name), " -T ' \r'"); system(command);

It writes a "space" and a "carriage return" to the current TTY. Which works fine for my uses. But, i'm wondering if there is a simpler way of achieving this? I've tried this:

echo -e " \r > $(tty)"

But, it isn't working.

2 Answers 2

2

You could instead open(2) /dev/tty and write to that:

#include <err.h>
#include <fcntl.h>
#include <stdio.h>

int main(void)
{
    int ttyfd;
    if ((ttyfd = open("/dev/tty", O_WRONLY)) == -1)
        err(1, "open /dev/tty failed");
    printf("test1\n");
    dprintf(ttyfd, " \rxxx");
    printf("test2\n");
    return 0;
}

(" \r" by itself may not be visible as it could be clobbered by the next written line.)

1

You could simply do (assuming the echo accepts the -n as "do not print a trailing new line") :

echo -ne " \r" > "$(tty)"

Redirections (>) do not work inside quotes.

A "one line" example:

$ echo -n Test; echo -ne " \r " > $(tty); echo "New string"
New string

A more robust (portable) solution is to use printf:

$ printf Test;     printf ' \r' > "$(tty)"    ; echo "New string"

And (as required by POSIX) use the common /dev/tty as the name of the process tty:

printf ' \r' > /dev/tty

Related: Does Posix require any devices?

1
  • Awesome. It's working. Thank you. I'm closing this thread.
    – ignatius
    Jun 15, 2018 at 21:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .