#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

enum { path_size = 64, buf_size = 4096 };

extern char **environ;

static void die(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void parse_environ_file()
{
    int pid, fd, res, count, i, j;
    char path[path_size], buf[buf_size];

    pid = getpid();
    sprintf(path, "/%s/%d/%s", "proc", pid, "environ");

    fd = open(path, O_RDONLY);
    if (fd == -1)
        die("open", 2);

    while ((count = read(fd, buf, buf_size)) != 0)
        for (i = 0, j = 0; j < count; j++)
            if (buf[j] == 0) {
                printf("%s\n", buf+i);
                i = j+1;
            }

    res = close(fd);
    if (res == -1)
        die("close", 2);
}

int main()
{
    char *editor;
    editor = getenv("EDITOR");
    if (editor) {
        printf("%s\n", editor);

        setenv("EDITOR", "vim", 1);
        editor = getenv("EDITOR");
        if (editor)
            printf("%s\n", editor);

    }

    memset(environ[0], 0, 600);
    parse_environ_file();
    editor = getenv("EDITOR");
    if (editor)
        printf("%s\n", editor);
    return 0;
}
