Anonymous user
Check output device is a terminal: Difference between revisions
Check output device is a terminal (view source)
Revision as of 12:27, 15 February 2024
, 4 months ago→{{header|Standard ML}}
imported>Regattaguru |
|||
(15 intermediate revisions by 9 users not shown) | |||
Line 1:
[[Category:Hardware]]
[[Category:Terminal control]]
[[Category:Initialization]]
{{task}}
;Task:
Line 12 ⟶ 13:
* [[Check input device is a terminal]]
<br><br>
=={{header|6502 Assembly}}==
{{works with|Commodore 64}}
<syntaxhighlight lang="6502asm">LDA $D011 ;screen control register 1
AND #%00100000 ;bit 5 clear = text mode, bit 5 set = gfx mode
BEQ isTerminal</syntaxhighlight>
=={{header|Ada}}==
{{works with|GNAT}}
We use the interface to C library functions <code>isatty()</code> and <code>fileno()</code>.
<
with Interfaces.C_Streams; use Interfaces.C_Streams;
Line 27 ⟶ 32:
Put_Line(Standard_Error, "stdout is a tty.");
end if;
end Test_tty;</
{{out}}
Line 37 ⟶ 42:
stdout is not a tty.
</pre>
=={{header|C}}==
Use <code>isatty()</code> on file descriptor to determine if it's a TTY. To get the file descriptor from a <code>FILE*</code> pointer, use <code>fileno</code>:
<
#include <stdio.h> // for fileno()
Line 51 ⟶ 55:
: "stdout is not tty");
return 0;
}</
{{out}}
Line 66 ⟶ 70:
stdout is not tty
</pre>
=={{header|C sharp|C#}}==
<
namespace CheckTerminal {
Line 76 ⟶ 79:
}
}
}</
=={{header|C++}}==
{{trans|C}}
<
#include <io.h>
#define ISATTY _isatty
Line 100 ⟶ 102:
return 0;
}</
=={{header|COBOL}}==
Works with GnuCOBOL.
<
*> istty, check id fd 0 is a tty
*> Tectonics: cobc -xj istty.cob
Line 130 ⟶ 131:
goback.
end program istty.</
DISPLAY for fd 1 is directed to SYSERR to get some output during the various trials.
Line 152 ⟶ 153:
fd 0 tty: +0000000000
fd 2 tty: +0000000000</pre>
=={{header|Common Lisp}}==
{{Works with|SBCL}}
<
(format T "stdout is~:[ not~;~] a terminal~%"
(interactive-stream-p s)))</
{{Out}}
Line 171:
We use the interface to C library functions <code>isatty()</code> and <code>fileno()</code>. It needs to be compiled to be executed.
<
#include <sys/ioctl.h>
#include <unistd.h>
Line 188:
(format T "stdout is~:[ not~;~] a terminal~%" (tty-p))
(quit)</
Compilation can be done with the following commands :
Line 201:
$ ./is-tty | cat -
stdout is not a terminal</pre>
=={{header|Crystal}}==
<
File.new("/dev/tty").tty? #=> true
STDOUT.tty? #=> true</
=={{header|D}}==
<
extern(C) int isatty(int);
Line 214 ⟶ 212:
void main() {
writeln("Stdout is tty: ", stdout.fileno.isatty == 1);
}</
{{out}}
Line 223 ⟶ 221:
Stdout is tty: false
</pre>
=={{header|Factor}}==
You have to know 1 is the correct file descriptor number:
<
IN: scratchpad USE: unix.ffi
IN: scratchpad 1 isatty
Line 232 ⟶ 229:
--- Data stack:
1
</syntaxhighlight>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Open Cons For Output As #1
' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar
' de la consola para leer o escribir.
If Err > 0 Then
Print #1, "stdout is not a tty."
Else
Print #1, "stdout is a tty."
End If
Close #1
Sleep
</syntaxhighlight>
=={{header|Go}}==
Tells a ''terminal'' apart from a ''pipe'' on Linux and Mac, which is probably exactly what you need.
<
import (
Line 250 ⟶ 260:
fmt.Println("Who are you? You're not a terminal")
}
}</
{{out}}
<pre>
Line 258 ⟶ 268:
Who are you? You're not a terminal.
</pre>
=={{header|Haskell}}==
<
-- requires the unix package
Line 274 ⟶ 283:
(if istty
then "stdout is tty"
else "stdout is not tty")</
{{Out}}
<pre>$ runhaskell istty.hs
Line 281 ⟶ 290:
stdout is not tty
</pre>
=={{header|J}}==
<
Explanation:
Line 297 ⟶ 305:
But, correctness requires us to keep in mind that these will only be heuristics, and will sometimes be incorrect (hopefully not often enough to matter a lot...).
=={{header|Javascript/NodeJS}}==
<
true</
=={{header|Julia}}==
<syntaxhighlight lang="julia">
if isa(STDOUT, Base.TTY)
println("This program sees STDOUT as a TTY.")
Line 309 ⟶ 315:
println("This program does not see STDOUT as a TTY.")
end
</syntaxhighlight>
{{out}}
Line 315 ⟶ 321:
This program sees STDOUT as a TTY.
</pre>
=={{header|Kotlin}}==
{{Works with|Ubuntu|14.04}}
<
import platform.posix.*
Line 327 ⟶ 332:
else
println("stdout is not a terminal")
}</
{{out}}
Line 333 ⟶ 338:
stdout is a terminal
</pre>
=={{header|Lua}}==
{{works with|Lua|5.1+}}
Using pure Lua, assuming a *NIX-like runtime environment ...
<
fd = tonumber( fd ) or 1
local ok, exit, signal = os.execute( string.format( "test -t %d", fd ) )
Line 345 ⟶ 349:
print( "stdin", isTTY( 0 ) )
print( "stdout", isTTY( 1 ) )
print( "stderr", isTTY( 2 ) )</
{{out}}
Line 371 ⟶ 375:
You can accomplish the same results using the luaposix [https://github.com/luaposix/luaposix] library:
<
local function isTTY ( fd )
Line 381 ⟶ 385:
print( "stdin", isTTY( 0 ) )
print( "stdout", isTTY( 1 ) )
print( "stderr", isTTY( 2 ) )</
The output of this version is identical to the output of the first version.
=={{header|Nemerle}}==
There is no explicit way (ie <tt>isatty()</tt>)to do this; however, if we ''assume'' that standard out ''is'' a terminal, we can check if the output stream has been redirected (presumably to something other than a terminal).
<
=={{header|Nim}}==
Using function "isatty" of standard module "terminal" which accepts a File as argument.
As we want to redirect stdout, we write the messages on stderr.
<
stderr.write if stdout.isatty: "stdout is a terminal\n" else: "stdout is not a terminal\n"</
{{out}}
Line 403 ⟶ 405:
<pre>Command: ./check_output_dev >somefile
Result: stdout is not a terminal</pre>
=={{header|OCaml}}==
<
print_endline (
if Unix.isatty Unix.stdout
then "Output goes to tty."
else "Output doesn't go to tty."
)</
Testing in interpreted mode:
Line 425 ⟶ 426:
Output doesn't go to tty.
</pre>
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(define (isatty? fd) (syscall 16 fd 19))
(print (if (isatty? stdout)
"stdout is a tty."
"stdout is not a tty."))
</syntaxhighlight>
=={{header|Perl}}==
The -t function on a filehandle tells you whether it's a terminal.
<
Terminal
$ perl -e "warn -t STDOUT ? 'Terminal' : 'Other'" > x.tmp
Other
</syntaxhighlight>
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no input or output redirection in a browser!)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"stdin:%t, stdout:%t, stderr:%t\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">isatty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span><span style="color: #000000;">isatty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">isatty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 452 ⟶ 460:
stdin:false, stdout:true, stderr:true
</pre>
=={{header|PHP}}==
<
if(posix_isatty(STDOUT)) {
echo "The output device is a terminal".PHP_EOL;
Line 460 ⟶ 467:
echo "The output device is NOT a terminal".PHP_EOL;
}
</syntaxhighlight>
=={{header|Python}}==
Pretty much the same as [[Check input device is a terminal#Python]].
<
if stdout.isatty():
print 'The output device is a teletype. Or something like a teletype.'
else:
print 'The output device isn\'t like a teletype.'</
=={{header|Quackery}}==
{{trans|Python}}
<syntaxhighlight lang="quackery"> [ $ |from sys import stdout
to_stack( 1 if stdout.isatty() else 0)|
python ] is ttyout ( --> b )
ttyout if
[ say "Looks like a teletype." ]
else
[ say "Not a teletype." ]</syntaxhighlight>
{{out}}
<pre>Looks like a teletype.</pre>
=={{header|Racket}}==
<
(terminal-port? (current-output-port))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
Line 483 ⟶ 503:
$ raku -e 'note $*OUT.t' >/dev/null
False</pre>
=={{header|REXX}}==
{{works with|PC/REXX under DOS or in a DOS window under MS Windows}}
{{works with|Personal REXX under DOS or in a DOS window under MS Windows}}
{{works with|Regina in a DOS window under MS Windows}}
Programming note: The comment about the REXX statements have to be on one line isn't quite true,
<br>but because the REXX special variable '''SIGL''' is defined where it's executed, it makes coding simpler.
'''SIGL''' is set to the REXX statement number where:
:::* a '''CALL''' statement is used
:::* a ''function'' is invoked
:::* a '''SIGNAL''' statement is used
Method used: since REXX has no direct way of determining if the STDIN is a terminal or not, the REXX code (below)
<br>actually ''raises'' (which is no way to run a railroad) a syntax error when attempting to read the 2<sup>nd</sup> line from STDIN,
<br>which causes a routine (named '''syntax:''') to get control, determines where the syntax error occurred, and returns
<br>an appropriate string indicating if STDIN is a '''terminal''' (or '''other''').
<br><br>Note that under VM/CMS, this can be accomplished with a (host) command within REXX and then examining the results.
<br>On IBM mainframes, a user can have STDIN defined, but the terminal can be ''disconnected''.
<syntaxhighlight lang="rexx">/*REXX program determines if the STDIN is a terminal device or other. */
signal on syntax /*if syntax error, then jump ──► SYNTAX*/
say 'output device:' testSTDIN() /*displays terminal ──or── other */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
testSTDIN: syntax.=1; signal .; .: z.= sigl; call linein ,2; ..: syntax.= 0; return z..
/* [↑] must/should be all on one line.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: z..= 'other' /*when a SYNTAX error occurs, come here*/
if syntax. then do /*are we handling STDIN thingy error?*/
if sigl==z. then z..= 'terminal'; signal .. /*is this a stdin ?*/
end /* [↑] can't use a RETURN here. */
/* ··· handle other REXX syntax errors here ··· */</syntaxhighlight>
{{out|output|text= when using the default input:}}
<pre>
output device: terminal
</pre>
{{works with|R4 REXX under DOS or in a DOS window under MS Windows}}
The following is the output when used with '''R4''' REXX:
{{out|output|text= when using the default input:}}
<pre>
Reading console input (Press Ctrl-Z to quit):
◄■■■■■■■■ user input (pressed ENTER)
◄■■■■■■■■ user input (pressed ENTER a 2nd time)
output device: 6
</pre>
=={{header|Ruby}}==
<
p f.isatty # => false
p STDOUT.isatty # => true
</syntaxhighlight>
=={{header|Rust}}==
<
extern crate libc;
Line 537 ⟶ 576:
println!("stdout is not tty");
}
}</
=={{header|Scala}}==
{{Works with|Ubuntu|14.04}}
<
object IsATty extends App {
Line 561 ⟶ 599:
println("tty " + apply(true))
}</
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">val stdoutRefersToTerminal : bool = Posix.ProcEnv.isatty Posix.FileSys.stdout</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="swift">print(isatty(STDOUT_FILENO) != 0 ? "TTY" : "Not TTY" )</syntaxhighlight>
=={{header|Tcl}}==
To detect whether output is going to a terminal in Tcl, you check whether the <code>stdout</code> channel looks like a serial line (as those are indistinguishable from terminals). The simplest way of doing that is to see whether you can read the <tt>-mode</tt> or <code>-xchar</code> channel options, which are only present on serial channels:
<
puts [expr {$toTTY ? "Output goes to tty" : "Output doesn't go to tty"}]</
At the system call level, when Tcl is setting up the channels that correspond to the underlying <tt>stdout</tt> (and <tt>stdin</tt> and <tt>stderr</tt>) file descriptors, it checks whether the channels are network sockets (with <code>getsockname()</code>) or serial lines (with <code>isatty()</code>). This allows Tcl scripts to find out information about their calling environment (e.g., when they are run from <tt>inetd</tt>) with minimal code.
{{out|Demonstrating}}
Line 576 ⟶ 618:
===Channel type discovery with older Tcl versions===
Before Tcl 8.4, this discovery process is impossible; <code>stdout</code> always looks like it is going to a file. With 8.4, you can discover the channel type but you need slightly different (and less efficient, due to the thrown error in the non-tty case) code to do it.
<
=={{header|UNIX Shell}}==
<
if [ -t 1 ]
Line 586 ⟶ 627:
else
echo "Output is NOT a terminal" >/dev/tty
fi</
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Main()
Line 596 ⟶ 636:
End Sub
End Module</
=={{header|Wren}}==
{{trans|C}}
As there is currently no way to obtain this information via Wren CLI, we instead embed a Wren script in a C application and ask the host program to get it for us.
<syntaxhighlight lang="wren">/* Check_output_device_is_a_terminal.wren */
class C {
foreign static isOutputDeviceTerminal
}
System.print("Output device is a terminal = %(C.isOutputDeviceTerminal)")</syntaxhighlight>
<br>
We now embed this Wren script in the following C program, compile and run it.
<syntaxhighlight lang="c">#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include "wren.h"
void C_isOutputDeviceTerminal(WrenVM* vm) {
bool isTerminal = (bool)isatty(fileno(stdout));
wrenSetSlotBool(vm, 0, isTerminal);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "isOutputDeviceTerminal") == 0) {
return C_isOutputDeviceTerminal;
}
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main() {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Check_output_device_is_a_terminal.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
{{out}}
<pre>
$ ./Check_output_device_is_a_terminal
Output device is a terminal = true
$ ./Check_output_device_is_a_terminal > tmp
$ cat tmp
Output device is a terminal = false
$ ./Check_output_device_is_a_terminal | cat
Output device is a terminal = false
</pre>
=={{header|zkl}}==
On Unix, check to see if stdout's st_mode is a character device.
<
fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() }
S_ISCHR(File.stdout).println();</
{{out}}
<pre>
Line 613 ⟶ 760:
False
</pre>
{{omit from|TI-83 BASIC|Output device is always either a terminal or created by the program}}
|