From 4f18100d731f35cd12b1ee01426959f16751313c Mon Sep 17 00:00:00 2001
From: "Tim J. Robbins" <tjr@FreeBSD.org>
Date: Tue, 4 Jun 2002 10:20:10 +0000
Subject: [PATCH] Respect setting of the COLUMNS environment variable (SUSv3)

---
 bin/ps/ps.1 | 10 ++++++++++
 bin/ps/ps.c |  5 ++++-
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/bin/ps/ps.1 b/bin/ps/ps.1
index 52d68ecab461..8e2debaacf18 100644
--- a/bin/ps/ps.1
+++ b/bin/ps/ps.1
@@ -506,6 +506,16 @@ wait channel (as a symbolic name)
 .It xstat
 exit or stop status (valid only for stopped or zombie process)
 .El
+.Sh ENVIRONMENT
+The following environment variables affect the execution of
+.Nm :
+.Bl -tag -width ".Ev COLUMNS"
+.It Ev COLUMNS
+If set, specifies the user's preferred output width in column positions.
+By default,
+.Nm
+attempts to automatically determine the terminal width.
+.El
 .Sh FILES
 .Bl -tag -width /var/db/kvm_kernel.db -compact
 .It Pa /dev/kmem
diff --git a/bin/ps/ps.c b/bin/ps/ps.c
index dbc9a14b7438..be31a9202ff5 100644
--- a/bin/ps/ps.c
+++ b/bin/ps/ps.c
@@ -123,12 +123,15 @@ main(int argc, char *argv[])
 	uid_t *uids;
 	int all, ch, flag, i, _fmt, lineno, nentries, dropgid;
 	int prtheader, wflag, what, xflg, uid, nuids;
+	char *cols;
 	char errbuf[_POSIX2_LINE_MAX];
 	const char *nlistf, *memf;
 
 	(void) setlocale(LC_ALL, "");
 
-	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
+	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
+		termwidth = atoi(cols);
+	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
 	     ws.ws_col == 0)