Here's /bin/env. (was: environment size question).

Joe Bob Willie haugj at pigs.UUCP
Thu Jul 14 08:51:45 AEST 1988


In article <1129 at sauron.Columbia.NCR.COM> wescott at sauron.Columbia.NCR.COM (Mike Wescott) writes:
>In article <249 at oha.UUCP> tony at oha.UUCP (Tony Olekshy) writes:
>> [ Source for /bin/env ]
>> #include <stdio.h>
>> main(c,a,e) char *a[],*e[]; { while (*e!=0) { puts(*e++); } exit(0); }
>
>That'll work fine if all you want out of /bin/env is to print the environment
>but how about the rest of the functionality of env?
>-- 
>	-Mike Wescott

well, mike, you asked for it.  here it is.  i wrote this whilst waiting
for pigs to crash.  it shouldn't have any bugs and i tested it somewhat.
try it on the cases which are known to cause the real env to bomb and
let me know how it works.  and this really is just a quick hack, at
70 someodd lines you can't expect the world.

- john.
--
/*
 * env - set environment for command execution
 *
 *	written by:	john f. haugh ii
 *	date:		13 july 88
 *	synopsis:	env [ - ] [ NAME=value ... ] [ command args ... ]
 *
 *	this is hereby placed into the public domain.  use at
 *	your own risk and all that nonsense.
 */

#include <stdio.h>
#include <string.h>

main (argc, argv, envp)
int	argc;
char	**argv;
char	**envp;
{
	char	**env;
	int	envc;
	int	lastenv;
	int	i;

	for (i = 0;envp[i] != (char *) 0;i++)
		;

	envc = i + argc;

	env = (char **) malloc ((envc + 1) * sizeof (char *));
	for (i = 0;i <= envc;i++)
		env[envc] = (char *) 0;

	argc--; argv++;			/* skip over program name */

	lastenv = 0;			/* nothing in the environment */

	if (argc > 0 && strcmp (*argv, "-") == 0) {
		argc--; argv++;
	} else {
		for (i = 0;envp[i] != (char *) 0;i++)
			env[lastenv++] = envp[i];
	}
	while (argc > 0) {
		if (strchr (*argv, '=') == (char *) 0) {
			execve (*argv, argv, env);
			perror (*argv);
			_exit (127);
		}
		for (i = 0;i < lastenv;i++)
			if (checkenv (*argv, env[i]))
				break;

		if (i < lastenv)
			env[i] = *argv;
		else
			env[lastenv++] = *argv;

		argc--; argv++;
	}
	for (i = 0;i < lastenv;i++)
		puts (env[i]);
}

checkenv (a, b)
char	*a;
char	*b;
{
	char	*aeq, *beq;
	int	len;

	if ((aeq = strchr (a, '=')) == (char *) 0 ||
			(beq = strchr (b, '=')) == (char *) 0)
		return (0);

	if (aeq - a != beq - b)
		return (0);

	return (! strncmp (a, b, aeq - a));
}
-- 
 John "Evil USENET User" F. Haugh II          HECI Exploration Co, Inc., Dallas
 UUCP: ...!killer!rpp386!jfh                            jfh at rpp386.UUCP :DOMAIN
 **** Trivia question of the day: VYARZERZIMANIMORORSEZASSEZANSERAREORSES? ****
 "You are in a twisty little maze of UUCP connections, all alike" -- fortune



More information about the Comp.unix.questions mailing list