May I set TERM environment variable safely? - c

I'm writing a program that uses termcaps and I need to know which kind of terminal I am using.
I am aware I can get TERM variable via getenv("TERM"), but I can launch my program with "$ env -i ./myprog" and TERM will not be set.
So how can I determine which terminal type must I use?
May I safely set TERM variable to xterm/xterm-256color in my application?
Will it cause non-portability issues?
Is there a method to do such (get termtype) safely?
I've red many manuals (getty - getttab - tty - ttys) and posts but I can't spot any solution.
I'm also worried because if I launch a shell (like zsh or tcsh) I have issues with some keys.
For example launching zsh like so:
$env -i zsh
will cause troubles with arrows and any keys implying termcaps (even Ctr-d).
Instead bash and tcsh will behave normally on many keys but not all.

If you're actually using termcap (and not some minimal implementation such as busybox), you're likely using a system that provides tset, which can offer the user a default choice for TERM that can be modified.
Something like this:
eval `tset -s vt100`
in the shell initialization would work.
Actually tset isn't limited to termcap-systems, but that's where it started.
Further reading:
tset, reset -- terminal initialization (FreeBSD)
tset, reset - terminal initialization (ncurses)
tset, reset - terminal initialization (NetBSD)

It is (somewhat) safe to set TERM=vt100 as default (Ctx's suggestion), as most terminal emulators are set to emulate that anyway. I'd recommend you to print a warning in this case, though.

Related

Is there a way to get help for some C functions inside of vim/Neovim?

This question may be a little off topic. But I was wondering if there was a way for me to look at the descriptions of C functions using vim or neovim. Is it possible to look at their documentations by doing something like :help? This would really be helpful since I wouldn't need to lookup to my browser everytime.
I am unclear about these things:
Can :help be my friend here ?
Can I use LSPs to do something like this ?
I am using latest Neovim inside Ubunutu 20.04 in WSL. Is this helpful somehow ?
By pressing K, the keyword under the cursor is looked up using a configured keyword lookup program, the default being man. This works pretty much out of the box for the C standard library.
For C++, you might want to look at something like cppman.
Well yes, you can get the description of C functions by using a LSP (language server plugin)! Here is an image of me using clangd as my LSP:
You'd "just" need to install the LSP and start it. I don't know how familiar you're with neovim, but just in case if you don't know how to install a plugin or to be more specifique: If you don't know how you can install a LSP server, then you can do the following:
There're plenty videos how to set up a LSP-Server for your language. Here's an example.
If you don't want to set up on your own, you can pick up one of the preconfigured neovim setups (some of my friends are recommending lunarvim)
But yeah, that's it. If you have any further questions feel free to ask them in the comments.
Happy vimming c(^-^)c
Let's explain how "K" command works in more detail.
You can run external commands by prefixing them with :! command. So running man tool is as easy as
:!man <C-R><C-W>
Here <C-R><C-W> is a special key combination used to put word under cursor from text buffer down to command line.
Same for showing Vim's built-in help page
:help <C-R><C-W>
As it feels tedious to type that, Vim also defines K Normal mode command that does pretty much the same thing. Except the tool name is taken from value of an option named "keywordprg".
So doing set keywordprg=man (default for *nix systems) makes K to invoke !man tool; while set keywordprg=:help is for bultin help.
Also, the option :h 'keywordprg' is made global or local-to-buffer, so any Vim buffer is able to overwrite global setting. For example, this is already done by standard runtime for "vim" and "help" buffers, so they call ":help" instead of "man".
The problem with :!man command is that it shows "black console". It'd be nice if we could capture man's output and open it inside Vim just like a builtin help page. Then we could also apply some pretty highlighting, assign key macros and all such. This is a pretty common trick and it is already done by a standard plugin shipped with Vim/Neovim.
A command that the plugin provides is called :Man, so you can open :Man man instead of :!man man, for example. The plugin is preactivated in Neovim; for Vim you still need to source one file manually. So to make use of this plugin you'll need something like this
set keywordprg=:Man
if !has("nvim")
source $VIMRUNTIME/ftplugin/man.vim
endif
The previous answer recommending cppman is the way to go. There is no need to install a bulky language server just for the purpose of having the hover functionality. However, make sure you're caching the man pages via cppman -c. Otherwise, there will be a noticeable delay since cppman is fetching the page from cppreference.com on the fly.
If you like popups for displaying documentation, convert the uncompressed man pages (groff -t -e -mandoc -Tascii <man-page> | col -bx), and set keywordprg to your own wrapper to search for keywords according to your needs.

Equivalent of bash's -x debug flag for C programs?

I always use the -x (or debug flag) when it come to bash script, or shell scripts in general.
Now i'm curious to know, is there an equivalent, either using a specific compiler options, (i use gcc, but i don't mind any other compilers) or by using a specific code in my project?
Basically i just wanted a way to emulate what bash does (using the debug flag) which show which command/function was launched first, in order, and also show the output of said function, with additional errors message etc.But for C.
I'm aware of most debug option out there, especially considering the compiler, but i really wish i could do this in my C projects too.(especially the part where it show what is executed in order, like bash does with -x)
NB: There isn't any goal in this specific question beside the question itself, as i'm just curious if this exist, and thus don't have any need for it beside the actual knowledge acquired from said answered question.
Yes, you can mimic this behaviour with a debugger.
With GDB for instance you can write "Init Files" and "Command Files" in which you can write a simple loop:
break main
run
while 1
next
end
If you put a file named .gdbinit in the directory where you start gdb, this file will be executed or gdb will lead you on the way to configure it in order that it will be executed.
The other option is to pipe this file into your gdb-call:
gdb a.out < debug_me_like-x
Where the "debug_me_like-x" file is the one mentioned above.
As a reference for the "Command Files" have a look here.

How do you execute a bash script with "system()" when there are spaces in the file path?

I created a simple bash script called "myscript.h" I gave it a .h extensions for reasons that I won't disclose here. This bash script lives in "/var/ftp/something with spaces".
From the terminal, I can type in "/var/ftp/something with spaces/myscript.h" and the script works perfectly.
However, from within my C program, I type in
system("/var/ftp/something with spaces/myscript.h")
and it complains that "/var/ftp/something" is not found. I've changed my system call to the following with forward slashes:
system("/var/ftp/something\ with\ spaces/myscript.h")
However, it still complains that "/var/ftp/something" is not found. Assuming I can't change the directory names, how can I get around this?
Thanks!
To run a single script, you might avoid the system(3) library function (and use lower level system calls like fork(2), execve(2), waitpid(2)... which are used by the implementation of system(3)), or you could quote the script name when passing it to system(3).
For more details, read Advanced Linux Programming.
On Linux, system(3) is documented to fork a /bin/sh -c process. See sh(1p). And that POSIX shell has some quoting rules. You might use double-quotes and backslashes appropriately. So you would construct (and perhaps check) the string passed to system(3) (perhaps using asprintf(3) or snprintf(3) with care). Be aware that the C compiler also has (different) quoting conventions for string literals.
In general, you should avoid code injection (imagine a naughty user giving some a; rm -rf $HOME &; input as a "directory" name; you don't want to run system(3) on the weird "/var/ftp/a; rm -rf $HOME &;/myscript.h" string)
In your particular case, I recommend using fork(2), execve(2) (perhaps thru some carefully choosen exec(3) function), waitpid(2)... appropriately. This has the slight advantage to avoid depending on and running /bin/sh so could be slightly faster (by a millisecond).
Understand more the role of an Unix shell; for example, read about the various shell expansions in bash (they are similar to those mandated by POSIX sh) and be aware of globbing. See glob(7)
Note that you're adding quotes when running from the shell. You need to do the same here. Add quotes to the path name you're sending to system:
system("\"/var/ftp/something with spaces/myscript.h\"")
This should work with gcc version 5.4.0
system("\'\'/var/ftp/something\\ with\\ spaces/myscript.h\'\'");
Just put the filename inside single quotes
system("rm '/var/ftp/something with spaces/myscript.h'")

ACS characters not working in putty even with export NCURSES_NO_UTF8_ACS=1

I am developing an ncurses application myself in C. The problem is that putty displays alternative character set characters like ACS_VLINE as letters. My locale is
LANG=en_US.UTF-8
and I have set
export NCURSES_NO_UTF8_ACS=1
I have also set putty to UTF-8 and tried different fonts. The characters display fine on the tty on the actual machine so I think the issue is with putty. I have also tried linking ncursesw instead of ncurses.
It is a combination of things. The recommended TERM for PuTTY is "putty", but due to inertia, most people use "xterm". The line-drawing support in the xterm terminal description is different from PuTTY's assumptions because xterm supports luit, which has some limitations with the way the alternate character set is managed (see Debian Bug report #254316:
ncurses-base: workaround for screen's handling of register sgr0 isn't quite right).
If you use infocmp to compare, you may see these lines which deal with the alternate character set:
acsc: '``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~', '``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~'.
enacs: NULL, '\E(B\E)0'.
rmacs: '\E(B', '^O'.
smacs: '\E(0', '^N'.
VT100s can have two character sets "designated", referred to as G0 and G1:
The "xterm" line-drawing works by changing the designation of G0 between the ASCII and line-drawing characters,
the "putty" line-drawing works by designating ASCII in G0 and line-drawing in G1 and switching between the two with the shift-in/shift-out control characters.
Although both are VT100-compatible, the xterm scheme does not work with PuTTY. Because of the tie-in with luit, the normal terminal description for xterm will not change (unless it proves possible to modify luit to solve the problem for its users), so a workaround is needed for users of PuTTY:
use a different terminal description as recommended, e.g., TERM=putty. PuTTY's settings dialog lets you set environment variables to pass to the remote machine.
This has the drawback that some systems do not have the full ncurses terminal database installed, due to "size" (it is 6.8Mb on my local machine). Also, TERM may not be on the list of allowed ssh environment variables.
you can compile your own terminfo entry with ncurses' tic, e.g.,
cat >foo <<"EOF"
xterm|my terminfo entry,
enacs=\E(B\E)0,
rmacs=^O,
smacs=^N,
use=xterm-new,
EOF
tic foo
use GNU screen. It does its own fixes, and happens to compensate for PuTTY's problems.
Further reading
SCS – Select Character Set (VT100 manual)
4.4 Character Set Selection (SCS) (VT220 manual)
The terminfo database is big—do I need all of that? (ncurses FAQ)
Putty: login, execute command/change environment variable, and do NOT close the session
I want to make some additions. I faced same issue: many ncurses-based tools like dialog, menuconfig and nconfig from Linux kenrel sources, even mc is broken when built with ncurses (although mc is built using Slang on many OSes and not affected).
Here is what happened
ncurses uses smacs record from terminfo to switch to "alternative charset" and then it uses acsc to draw boxes. It sends a which is box-drawing character in alternative charset (ACS).
This is VT100 graphics.
Some terminal emulators nowadays do not support ACS when in UTF-8 because apps have ability to send real box-drawing codepoints.
There is unofficial capability U8 (capital U!) in terminfo that tells ncurses: "Instead of ACS use real box-drawing codepoints."
I have this capability infocmp -x xterm-utf and for putty aswell, but not for xterm.
As you can read in ncurses(3) (https://invisible-island.net/ncurses/man/ncurses.3x.html), ncurses is aware of Linux console and GNU screen (and tmux, which also uses screen as TERM) and always behave like if U8 were set.
For other terminals that do not support ACS when in UTF, you can set NCURSES_NO_UTF8_ACS.
Unfortunatelly, ncurses is not aware of putty.
There is also luit that may convert ACS to Unicode points.
So, here is what we can do to run ncurses + putty in UTF-8:
Use terminal with U8#1 capability. This one is set for putty (btw, I suggest to use putty-256color instead). You can create your own entry with U8#1 and colors#256 and compile it with tic -x. Be carefull that mouse may not work on terminals that do not start with xterm (see mouseinterval(3), BUGS section). This is why I do not use putty terminal. I suggest to copy xterm-utf8, add colors#256, compile and stay with it: it works perfectly with putty, mouse and utf8.
You can set NCURSES_NO_UTF8_ACS in your profile.
You can run screen or tmux: it will set TERM to screen and fix ncurses
You can run luit: it will do all convertions for you.
Since putty 0.71 you can ask putty to support ACS drawings even in UTF-8

Why does GDB start a new shell and how to disable this behaviour?

I was figuring out a problem where starting the application from GDB results in a symbol lookup error, but starting it from the shell works.
It turns out that whenever you start a program from within GDB it will start a new shell and thus override all environment variables I had set before starting GDB (like LD_LIBRARY_PATH).
This is not really the behavior I want. Can someone explain the rationale behind this, or tell me how I can turn this off?
I am guessing that you unconditionally set LD_LIBRARY_PATH in your ~/.cshrc or the like. So if from a shell prompt you do this:
export LD_LIBRARY_PATH=foo # or for csh:
setenv LD_LIBRARY_PATH foo
$SHELL -c 'echo $LD_LIBRARY_PATH'
the result is something other than foo. Don't do that.
Usually this happens to CSH users, who neglected to protect their ~/.cshrc against non-interactive shells. It could also happen to BASH users who set their BASH_ENV.
I meet the same problem. I find that in inferior.h (source code of gdb gdb/inferior.h)
there is a macro STARTUP_WITH_SHELL, there is also a piece of comment as
/* If STARTUP_WITH_SHELL is set, GDB's "run"
will attempts to start up the debugee under a shell.
This is in order for argument-expansion to occur. E.g.,
(gdb) run *
The "*" gets expanded by the shell into a list of files.
While this is a nice feature, it turns out to interact badly
with some of the catch-fork/catch-exec features we have added.
In particular, if the shell does any fork/exec's before
the exec of the target program, that can confuse GDB.
To disable this feature, set STARTUP_WITH_SHELL to 0.
To enable this feature, set STARTUP_WITH_SHELL to 1.
The catch-exec traps expected during start-up will
be 1 if target is not started up with a shell, 2 if it is.
- RT
If you disable this, you need to decrement
START_INFERIOR_TRAPS_EXPECTED in tm.h. */
#define STARTUP_WITH_SHELL 1
#if !defined(START_INFERIOR_TRAPS_EXPECTED)
#define START_INFERIOR_TRAPS_EXPECTED 2
#endif
Then I set STARTUP_WITH_SHELL as 0 and decremented START_INFERIOR_TRAPS_EXPECTED
and recompiled my gdb. After that gdb didn't start from shell any more.
When you start gdb from the shell, you start it as a new process, there's no way around that. In Unix new processes inherit some of the environment of the parent.
To make sure a variable is inherited, if you're using a bourne-like shell, try exporting it:
export LD_LIBRARY_PATH=...
The debuggee (inferior in gdb parlance) is always started with a clean environment in order to get more reproducible results. In order to set a variable there, use the
set env VARNAME=VALUE
command before running.

Resources