Search code examples
c++raspberry-pirootsudogetenv

getenv("HOME") returns "/root" with "sudo"


I'm writing a program on my Raspberry Pi that requires the function "getenv("HOME")" to locate "/home/pi".

However, since I'm using the "wiringPi" library that requires "sudo" to run, "getenv("HOME")" now returns "/root" as the HOME directory instead of "/home/pi".

Is there a way to locate "/home/pi" with "getenv("HOME")" while using "sudo" the run the program?

Any help will be appreciated. Thank you.


Solution

  • Transferring comments and response into an answer.

    If you know the answer is /home/pi, why do you need getenv("HOME") to get the wrong value?

    It's because getenv("HOME") is the code from another library I am trying to run, which I cannot change.

    Presumably, calling setenv("HOME", "/home/pi", 1) is a bit too much like cheating, too?

    setenv("HOME", "/home/pi", 1) works for me.

    Why are you sure that the value you need is /home/pi? Why isn't /root correct when the program is run by root (or someone running sudo)?

    This becomes mostly immaterial given that there's another unchangeable library involved.

    In that case, setting the correct value for the environment variable before invoking the other library is a mostly reasonable mechanism.