-1

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.

K.Y. L
  • 3
  • 3
  • 2
    If you know the answer is `/home/pi`, why do you need `getenv("HOME")` to get the wrong value? Presumably, calling `setenv("HOME", "/home/pi", 1)` is a bit too much like cheating, too? 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`)? – Jonathan Leffler Mar 12 '15 at 02:59
  • There are many things you could do, including adding a command line option to your program to override use of `$HOME`, setting `$HOME` before running your program, looking first for a `$HOME_OVERRIDE` variable etc.. – Tony Delroy Mar 12 '15 at 03:01
  • It's because "getenv("HOME")" is the code from another library I am trying to run, which I cannot change. **setenv("HOME", "/home/pi", 1)** works for me, thanks @Jonathan Leffler. – K.Y. L Mar 12 '15 at 03:32

1 Answers1

1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278