Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getenv Not Working for COLUMNS and LINES

I am trying to get the number of columns and lines in my program. I am using the following code to do so:

...

char *cols = getenv("COLUMNS");
printf("cols: %s\n", cols);

char *lines = getenv("LINES");
printf("lines: %s\n", lines);

...

The problem is that when I run this I get null for both. Running this with other environment variables, such as PATH or USER, works fine.

What I find strange is that running echo $COLUMNS and echo $LINES from the same shell both work fine.

Why is my program unable to get these two environment variables.

like image 623
carloabelli Avatar asked Mar 23 '14 07:03

carloabelli


People also ask

Why would Getenv return null?

java - System. getenv() returns null when the environment variable exists - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

How do I permanently set environment variables?

You can set an environment variable permanently by placing an export command in your Bash shell's startup script " ~/. bashrc " (or "~/. bash_profile ", or " ~/. profile ") of your home directory; or " /etc/profile " for system-wide operations.

What does the Getenv function do?

The getenv() function returns a pointer to the string containing the value for the specified varname in the current environment. If getenv() cannot find the environment string, NULL is returned, and errno is set to indicate the error.

Is Getenv a system call?

If your getenv function call is invisible to it, it is not a system call.


2 Answers

COLUMNS and LINES are set by the shell, but not exported, which means that they are not added to the environment of subsequently executed commands. (To verify that, examine the output of /usr/bin/env: it will show PATH and USER, but not COLUMNS and LINES.)

In the bash shell, you can call export VAR to mark a variable for export.

Alternatively, see Getting terminal width in C? for various ways to obtain the terminal width and height programmatically.

like image 66
Martin R Avatar answered Sep 29 '22 19:09

Martin R


If you don't see $LINES and $COLUMNS, they are probably not set. The xterm manual page states they may be set, depending on system configuration.

If you want to see what environment variables are passed to your program, use this little program (which uses the third, nonstandard "hidden" parameter to main() which should be available on all IXish systems:

#include <stdio.h>

int main(int argc, char *argv[], char *envp[])
{
    while (*envp)
    {
        printf("%s\n", *envp++);
    }   
}

If you want a portable way to obtain your terminal window size, its probably best to use ioctl(..., TIOCGWINSZ, ...)

like image 31
mfro Avatar answered Sep 29 '22 21:09

mfro