Check output device is a terminal: Difference between revisions

Content added Content deleted
(Added a solution for D)
Line 79: Line 79:
$ sbcl --script rc.lisp > foo.txt
$ sbcl --script rc.lisp > foo.txt
$ cat foo.txt
$ cat foo.txt
stdout is not a terminal</pre>

{{Works with|ECL}}
We use the interface to C library functions <code>isatty()</code> and <code>fileno()</code>. It needs to be compiled to be executed.

<lang lisp>(ffi:clines "
#include <sys/ioctl.h>
#include <unistd.h>
int ttyPredicate() {
return isatty(fileno(stdout));
}")

(ffi:def-function
("ttyPredicate" c-ttyp)
() :returning :int)

(defun tty-p()
(if (= 1 (c-ttyp))
t
nil))

(format T "stdout is~:[ not~;~] a terminal~%" (tty-p))
(quit)</lang>

Compilation can be done with the following commands :

<code>ecl --eval '(compile-file "file.lisp" :system-p t)' --eval '(quit)'</code>

<code>ecl --eval '(c:build-program "is-tty" :lisp-files (list "file.o"))' --eval '(quit)'</code>

{{Out}}
<pre>$ ./is-tty
stdout is a terminal
$ ./is-tty | cat -
stdout is not a terminal</pre>
stdout is not a terminal</pre>