0

I'm currently building a daemon in C++ and the children processes are created by a fork() statement. The children are listening incoming events from an Amazon SQS queue, and everything is working fine in the lifetime loop of the processes.

When a new message is read from the queue, the process must execute an external binary (already compiled in c++ with dynamic librairies). The execution of this binary is made by a system(my_binary_path); statement.

The thing is that the binary needs the DYLD_LIBRARY_PATH to be already set in the execution environment but it is not (because the execution is made by the child process and not the current user session).

I already tried to export the DYLD_LIBRARY_PATH env variable directly from the system("export DYLD_LIBRARY_PATH=<path-to-my-dylib-folder>") function. I also tried to set it through the setenv("DYLD_LIBRARY_PATH", <path-to-my-dylib-folder>) function, that didn't work either.

I don't know what's the correct way to set the env variable or make this working with dynamic librairies or if there's any other alternative to execute the external binary.

Thank you for your help in advance.

Sense
  • 1,096
  • 8
  • 20
  • https://stackoverflow.com/questions/245600/using-a-single-system-call-to-execute-multiple-commands-in-c – VLL Sep 01 '20 at 09:27
  • https://unix.stackexchange.com/a/289517/31736 – Marek R Sep 01 '20 at 09:29
  • 3
    Instead of using `system`, you can always use fork and one of the [`exec`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html) family of functions that explicitly pass the environment. – Useless Sep 01 '20 at 09:33
  • Instead of treating the symptoms, treat the disease by correctly configuring the RPATH of your binary. – Botje Sep 01 '20 at 09:38
  • Also, DYLD is for macOS. Did you mean `LD_LIBRARY_PATH` for Linux? – Botje Sep 01 '20 at 09:39

1 Answers1

1

You need to run a single system() call which sets the environment variable and runs the program. Do it like this:

system("DYLD_LIBRARY_PATH=<path-to-my-dylib-folder> my_binary_path")

The same syntax works in a regular shell: the variable is set for the specified command (and not afterward).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436