[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: /etc/environment



Adam P. Harris <apharris@onshore.com> wrote:
> Also, it's not that simple:  remember csh users?

Here's a solution which will work for any executable (except that
the executable may proceed to trash its environment -- you have to
address that kind of thing on a case by case basis):

-- 
Raul

/* usage:
   first arg is absolute path of executable to run
   remaining args will be passed to that program

   This program stuffs everything from /etc/environment
   in the environment before running argument executable
   */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <setjmp.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>

jmp_buf context;
die(msg) {
	perror("msg");
	longjmp(context, 1);
}

main(int argc, char**argv, char**env) {
	char**new_env= env;
	if (!setjmp(context)) {
		int fd= open("/tmp/environment", O_RDONLY);
		struct stat statbuf;
		ssize_t size, offset;
		int lines, newlines, j;
		char*buf;
		char**env2;

		if (-1 == fd) die("open(\"/tmp/environment\")");
		if (fstat(fd, &statbuf)) die("stat(\"/tmp/environment\")");
		size= statbuf.st_size;
		buf= (char*)malloc(size);
		if (!buf) die("buf=malloc()");
		offset=0;
		while (offset<size) {
			ssize_t n= read(fd, buf, size-offset);
			if (-1 == n) {
				if (EAGAIN!=errno) die("read()");
				continue;
			}
			if (!n) {
				fputs("race condition\n", stderr);
				longjmp(context, 1);
			}
			offset+= n;
		}
		for (newlines=0, j=0; j<size; j++) {
			if ('\n' == buf[j]) {
				buf[j]= 0;
				newlines++;
			}
		}
		for (lines=newlines, j=0; env[j]; j++) {
			lines++;
		}
		env2=(char**)malloc((1+lines)*sizeof*env2);
		if (!env2) die("env2=malloc()");
		new_env=env2;
		*env2++= buf;
		for (j=0; j<newlines; buf++) {
			if (!*buf) {
				*env2++= buf+1;
				j++;
			}
		}
		env2--; /* nothing good after last line of file */
		for (j=0; (newlines+j) <= lines; j++) {
			env2[j]= env[j];
		}
	}
	execve(argv[1], argv+1, new_env);
	perror("execve");
	exit(1);
}


--
TO UNSUBSCRIBE FROM THIS MAILING LIST: e-mail the word "unsubscribe" to
debian-devel-request@lists.debian.org . 
Trouble?  e-mail to templin@bucknell.edu .


Reply to: