I cannot get environment variable in my PostgreSQL C extension code.

For example, this function always returns 111:

#include "postgres.h"
#include "fmgr.h"
#include <stdlib.h>


  int32 arg = PG_GETARG_INT32(0);
  char* envar = getenv("MYINC");
  if (envar) {
    PG_RETURN_INT32(arg + atoi(envar));
  } else {

While this C program works as expected, it prints whatever MYINC is:

#include <stdio.h>
#include <stdlib.h>

int main()
  printf("MYINC: %s", getenv("MYINC"));
  return 0;

1 Answer 1


That should work just fine. Note, however, that it will take the variable from the environment of the PostgreSQL server process, not your current client process.

  • 1
    How do I save variable to the environment of the PostgreSQL server process? I've tried adding it to /etc/environment and also to ~/.profile (with restart of PostgreSQL service and even with PC restart) but it didn't work. I'm using Ubuntu via WSL2.
    – Nikola
    Jan 18 at 17:48
  • 1
    As far as I remember, the Ubuntu PostgreSQL binaries have a special environment file under /etc/postgresql. Jan 19 at 6:47
  • It works. Thank you Albe!
    – Nikola
    Jan 19 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.