EzDevInfo.com

tty.js

A terminal for your browser, using node/express/socket.io

How do I detect if stdout is connected to a tty in Perl?

I'm looking for the Perl equivalent to this Python code:

from sys import stdout
if stdout.isatty():
    print "yes"
else:
    print "no"

Source: (StackOverflow)

How to toggle CR/LF in gnu screen?

I'm using screen to read the text from a serial console. The problem is the output seems to only have newline \n but not carriage return \r, so the display looks like this...

Line1
     Line2
          Line3

I wonder if there is any patch to fix this issue?


Source: (StackOverflow)

Advertisements

How to know which device is connected in which /dev/ttyUSB port

I am using two wavecom modem having 16 ports in each. When i attach modem with my machine, i am able to get list of all /dev/ttyUSB port name, but i want to know also, which modem is containing port 0 to 16 and which one is containing 17 to 32 ?

This modem is going to attached and removed many time in single day, so i also want to keep watch , when modem get disconnected and connected again ?

Any idea how to do so using c/c++/php script/node.js ?


Source: (StackOverflow)

Receiving key press and key release events in Linux terminal applications?

I would like to write a simple C program that will perform different actions based on both "key down" and "key up" events. This program will be run from inside rxvt.

What library or mechanism should I use to access both key presses and releases? Is it true that reading /dev/tty will only provide key releases? Is this also true for termcap, terminfo, ncurses, and slang? Is there a way to achieve this from within a terminal application?


Source: (StackOverflow)

Docker - Enter Running Container with new TTY

I have a container that is running the Apache service in the foreground. I would like to be able to access the container from another shell in order to "poke around" inside it and examine the files. At the moment, if I attach to the container, I am left looking at the Apache daemon and cannot run any commands.

Is it possible to attach another tty to a running container? Possibly, I can take advantage of the fact that Docker is actually just wrapping around LXC containers? I have tried sudo lxc-console -n [container-id] -t [1-4] but it appears that only one tty is made available and that is the one running the apache daemon. Perhaps there is a way to enable multiple lxc consoles during the build?

I would rather not configure and build the container with an openssh service if possible.


Source: (StackOverflow)

Why is printing to stdout so slow? Can it be sped up?

I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting for the terminal to process the results.

Can writing to stdout be sped up somehow?

I wrote a script ('print_timer.py' at the bottom of this question) to compare timing when writing 100k lines to stdout, to file, and with stdout redirected to /dev/null. Here is the timing result:

$python print_timer.py
this is a test
this is a test
<snipped 99997 lines>
this is a test
-----
timing summary (100k lines each)
-----
print                         :11.950 s
write to file (+ fsync)       : 0.122 s
print with stdout = /dev/null : 0.050 s

Wow. To make sure python isn't doing something behind the scenes like recognizing that I reassigned stdout to /dev/null or something, I did the redirection outside the script...

$ python print_timer.py > /dev/null
-----
timing summary (100k lines each)
-----
print                         : 0.053 s
write to file (+fsync)        : 0.108 s
print with stdout = /dev/null : 0.045 s

So it isn't a python trick, it is just the terminal. I always knew dumping output to /dev/null sped things up, but never figured it was that significant!

It amazes me how slow the tty is. How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?

This link talks about how the terminal will block I/O so it can "parse [the input], update its frame buffer, communicate with the X server in order to scroll the window and so on"... but I don't fully get it. What can be taking so long?

I expect there is no way out (short of a faster tty implementation?) but figure I'd ask anyway.


UPDATE: after reading some comments I wondered how much impact my screen size actually has on the print time, and it does have some significance. The really slow numbers above are with my Gnome terminal blown up to 1920x1200. If I reduce it very small I get...

-----
timing summary (100k lines each)
-----
print                         : 2.920 s
write to file (+fsync)        : 0.121 s
print with stdout = /dev/null : 0.048 s

That is certainly better (~4x), but doesn't change my question. It only adds to my question as I don't understand why the terminal screen rendering should slow down an application writing to stdout. Why does my program need to wait for screen rendering to continue?

Are all terminal/tty apps not created equal? I have yet to experiment. It really seems to me like a terminal should be able to buffer all incoming data, parse/render it invisibly, and only render the most recent chunk that is visible in the current screen configuration at a sensible frame rate. So if I can write+fsync to disk in ~0.1 seconds, a terminal should be able to complete the same operation in something of that order (with maybe a few screen updates while it did it).

I'm still kind of hoping there is a tty setting that can be changed from the application side to make this behaviour better for programmer. If this is strictly a terminal application issue, then this maybe doesn't even belong on StackOverflow?

What am I missing?


Here is the python program used to generate the timing:

import time, sys, tty
import os

lineCount = 100000
line = "this is a test"
summary = ""

cmd = "print"
startTime_s = time.time()
for x in range(lineCount):
    print line
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)

#Add a newline to match line outputs above...
line += "\n"

cmd = "write to file (+fsync)"
fp = file("out.txt", "w")
startTime_s = time.time()
for x in range(lineCount):
    fp.write(line)
os.fsync(fp.fileno())
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)

cmd = "print with stdout = /dev/null"
sys.stdout = file(os.devnull, "w")
startTime_s = time.time()
for x in range(lineCount):
    fp.write(line)
t = time.time() - startTime_s
summary += "%-30s:%6.3f s\n" % (cmd, t)

print >> sys.stderr, "-----"
print >> sys.stderr, "timing summary (100k lines each)"
print >> sys.stderr, "-----"
print >> sys.stderr, summary

Source: (StackOverflow)

What do pty and tty mean?

I noticed there are many mentions of pty and tty in some opensource projects, could someone can tell me what do they mean and what is the difference between them? Thanks!


Source: (StackOverflow)

How to fix 'sudo: no tty present and no askpass program specified' error?

I am trying to compile some sources using a makefile. In the makefile there is a bunch of commands that need to be ran as sudo.

When I compile the sources from a terminal all goes fine and the make is paused the first time a sudo command is ran waiting for password. Once I type in the password make resumes and completes.

But I would like to be able to compile the sources in NetBeans. So, I started a project and showed netbeans where to find the sources, but when I compile the project it gives the error:

sudo: no tty present and no askpass program specified

The first time it hits a sudo command.

I have looked up the issue on the internet and all the solutions I found point to one thing: disabling the password for this user. Since the user in question here is root. I do not want to do that.

Is there any other solution?


Source: (StackOverflow)

MacOS: what's the difference between /dev/tty.* and /dev/cu.*?

Each serial device shows up twice in /dev, once as a tty.* and once as a cu.*.

What is the cu.* device? How does it differ from the tty.* device?

mh@maru ~ --> ls -l /dev/*.usbmodem621
crw-rw-rw-  1 root  wheel   11,   5 Dec 25 18:00 /dev/cu.usbmodem621
crw-rw-rw-  1 root  wheel   11,   4 Dec 25 18:00 /dev/tty.usbmodem621

Source: (StackOverflow)

Linux C Serial Port Reading/Writing

I'm trying to send/receive data over an USB Port using FTDI, so I need to handle serial communication using C/C++. I'm working on Linux (Ubuntu).

Basically, I am connected to a device which is listening for incoming commands. I need to send those commands and read device's response. Both commands and response are ASCII characters.

Everything works fine using GtkTerm but, when I switch to C programming, I encounter problems.

Here's my code:

#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>    // POSIX terminal control definitions

/* Open File Descriptor */
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NONBLOCK | O_NDELAY );

/* Error Handling */
if ( USB < 0 )
{
cout << "Error " << errno << " opening " << "/dev/ttyUSB0" << ": " << strerror (errno) << endl;
}

/* *** Configure Port *** */
struct termios tty;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 )
{
cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << endl;
}

/* Set Baud Rate */
cfsetospeed (&tty, B9600);
cfsetispeed (&tty, B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;        // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;
tty.c_cflag     &=  ~CRTSCTS;       // no flow control
tty.c_lflag     =   0;          // no signaling chars, no echo, no canonical processing
tty.c_oflag     =   0;                  // no remapping, no delays
tty.c_cc[VMIN]      =   0;                  // read doesn't block
tty.c_cc[VTIME]     =   5;                  // 0.5 seconds read timeout

tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
tty.c_iflag     &=  ~(IXON | IXOFF | IXANY);// turn off s/w flow ctrl
tty.c_lflag     &=  ~(ICANON | ECHO | ECHOE | ISIG); // make raw
tty.c_oflag     &=  ~OPOST;              // make raw

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );

if ( tcsetattr ( USB, TCSANOW, &tty ) != 0)
{
cout << "Error " << errno << " from tcsetattr" << endl;
}

/* *** WRITE *** */

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
int n_written = write( USB, cmd, sizeof(cmd) -1 );

/* Allocate memory for read buffer */
char buf [256];
memset (&buf, '\0', sizeof buf);

/* *** READ *** */
int n = read( USB, &buf , sizeof buf );

/* Error Handling */
if (n < 0)
{
     cout << "Error reading: " << strerror(errno) << endl;
}

/* Print what I read... */
cout << "Read: " << buf << endl;

close(USB);

What happens is that read() returns 0 (no bytes read at all) or block until timeout (VTIME). I'm assuming this happens because write() does not send anything. In that case, device wouldn't receive command and I cannot receive response. In fact, turning off the device while my program is blocked on reading actually succeded in getting a response (device sends something while shutting down).

Strange thing is that adding this

cout << "I've written: " << n_written << "bytes" << endl; 

right after write() call, I receive:

I've written 6 bytes

which is exactly what I expect. Only my program doesn't work as it should, like my device cannot receive what I'm actually writing on port.

I've tried different things and solution, also regarding data types (I've tried using std::string, such as cmd = "INIT \r" or const char) but nothing really worked.

Can someone tell me where I'm wrong?

Thank you in advance.

EDIT: Previously version of this code used

unsigned char cmd[] = "INIT \n"

and also cmd[] = "INIT \r\n". I changed it because command sintax for my device is reported as

<command><SPACE><CR>.

I've also tried avoiding the O_NONBLOCK flag on reading, but then I only block until forever. I've tried using select() but nothing happens. Just for a try, I've created a waiting loop until data is avaliable, but my code never exit the loop. Btw, waiting or usleep() is something I need to avoid. Reported one is only an excerpt of my code. Complete code needs to work in a real-time environment (specifically OROCOS) so I don't really want sleep-like function.


Source: (StackOverflow)

Piping data to Linux program which expects a TTY (terminal)

I have a program in Linux which refuses to run if its stdin/stdout is not a TTY (terminal device). Is there an easy-to-use tool which will create a PTY, start the program with the newly created TTY, and copy all data over stdin/stdout?

The use case is not interactive, but scripting. I'm looking for the most lightweight solution, preferably not creating TCP connections, and not requiring too many other tools and libraries to be installed.


Source: (StackOverflow)

Vagrant is attempting to interface with the UI in a way that requires a TTY

Problem: vagrant up fails with the error below. I am running vagrant on Windows 7 and the base box is Ubuntu )( files.vagrantup.com/precise32.box ).

how can it be fixed?

    vagrant.bat up

Bringing machine 'default' up with 'virtualbox' provider...
[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) Intel(R) PRO/1000 EB Network Connection with I/O Acceleration
2) Intel(R) PRO/1000 PL Network Connection
Vagrant is attempting to interface with the UI in a way that requires
a TTY. Most actions in Vagrant that require a TTY have configuration
switches to disable this requirement. Please do that or run Vagrant
with TTY.

Process finished with exit code 1

thanks


Source: (StackOverflow)

How can I implement timeout for read() when reading from a serial port (C/C++)

I am reading bytes from a serial port in C++ using a file descriptor and the posix/unix read() function. In this example, I am reading 1 byte from the serial port (baud rate settings and similiar are omitted for clarity):

#include <termios.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
{
   int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
   char buf[1];
   int bytesRead = read(fd, buf, 1);
   close(fd);
   return 0;
}

If the device connected to /dev/ttyS0 does not send any information, the program will hang. How can I set a timeout?

I have tried setting a time out like this:

struct termios options;
tcgetattr(fd, &options);
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &options);

I thought it was supposed to give 1 second timeout, but it makes no difference. I think I have misunderstood VMIN and VTIME. What is VMIN and VTIME used for?

Then I searched the web and found somebody talking about the select() function. Is that the solution and if so, how would one apply that to the program above to make 1 second timeout?

Any help is appreciated. Thanks in advance :-)


Source: (StackOverflow)

Why does ssh wait for my subshells without -t, and kill them with -t?

I have a bash script start.sh which looks like this:

for thing in foo bar; do
    {
        background_processor $thing
        cleanup_on_exit $thing
    } &
done

This does what I want: I run start.sh, it exits with code 0, and the two subshells run in the background. Each subshell runs background_processor, and when that exits, it runs cleanup_on_exit. This works even if I exit the terminal from which I originally ran start.sh (even if that was an ssh connection).

Then I tried this:

ssh user@host "start.sh"

This works, except that after start.sh has exited, ssh apparently also waits for the subshells to exit. I don't really understand why. Once start.sh exits, the subshells become children of pid 1, and they are not even assigned with a tty... so I can't understand how they are still associated with my ssh connection.

I later tried this:

ssh -t user@host "start.sh"

Now the processes have an assigned pseudo-tty. Now, I find that ssh does exit as soon as start.sh exits, but it also kills the child processes.

I guessed that the child processes were being sent SIGHUP in the latter case, so I did this:

ssh -t user@host "nohup start.sh"

That actually works! So, I have a solution to my practical problem, but I would like to grasp the subtleties of the SIGHUP/tty stuff here.

In summary, my questions are:

  1. Why does ssh (without -t) wait for the child processes even after start.sh exits, even though they have parent pid 1?
  2. Why does ssh (with -t) kill the child processes, apparently with a SIGHUP, even though that does not happen when I run them from a terminal and log out of that terminal?

Source: (StackOverflow)

Get terminal size in Go

How to get tty size with Go lang? I am trying do this with executing stty size command, but i can't craft code right.

package main

import (
  "os/exec"
  "fmt"
  "log"
)

func main() {
  out, err := exec.Command("stty", "size").Output()
  fmt.Printf("out: %#v\n", out)
  fmt.Printf("err: %#v\n", err)
  if err != nil {
    log.Fatal(err)
  }
}

Output:

out: []byte{}
err: &exec.ExitError{ProcessState:(*os.ProcessState)(0xc200066520)}
2013/05/16 02:35:57 exit status 1
exit status 1

I think this is because Go spawns a process not related to the current tty, with which it is working. How can I relate the command to current terminal in order to get its size?


Source: (StackOverflow)