Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't use "/usr/bin/env" in C execve() call on macOS

I couldn’t really find any relevant results after looking for a while, so I’m asking this myself. I have the following C code, which tries to execute nasm through execve() via /usr/bin/env so I don’t have to hardcode the path to the executable.

#include <unistd.h>
int main(int argc, char**argv) {
    char *cmds[10] = {"/usr/bin/env", "nasm", "--version", NULL};
    execve(cmds[0], cmds, NULL);
}

On linux (Ubuntu 18/20), it works fine:

linux $ gcc test.c && ./a.out
NASM version 2.13.02
linux $

However, on macOS (Catalina, at least), I get the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

macos $ gcc test.c && ./a.out                                                                                                                            
env: nasm: No such file or directory
macos $

I’m not exactly sure what the difference is. I do have NASM installed, I can run nasm --version on my terminal just fine. It also works fine if I hardcode the path /usr/local/bin/nasm to the execve() call. If I try to run the following manually on my terminal, it also seems to work:

macos $ /usr/bin/env nasm --version
NASM version 2.15.05 compiled on Aug 29 2020
macos $

The reason I want to use /usr/bin/env is that the default install location for nasm is different for different OSs, and I don’t want to just hardcode the paths.

>Solution :

The problem is that you use execve.

The e suffix means you pass an environment to the exec system call, but the environment you pass is NULL. Which means no environment at all.

Use execv instead to use the same environment as the calling program.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading