Follow

Does anyone know if it is possible to call posix_spawn or posix_spawnp with a custom PATH? I could hack environ, but that isn't thread safe. Trying to see if I can't move away from fork -> posix_spawn but need to be able to set custom PATH for launching processes!

@sheredom I think you would do your own path search, and then call posix_spawn with an absolute path to the executable. Is there a library function to do the path walk?

@stoklund Yeah - but at that point will it be faster than doing fork() then setting environ then calling execve? I guess not!

@sheredom Yeah, I think posix_spawn() can potentially be faster than fork/exec because it doesn’t have to clone your process state - address space, file tables, etc, only for you to redo all the setup before calling execve(). It’s not just having the path search in-kernel.

But fork() is super-optimized in Linux at least, so I don’t know if there’s a big win. It’s even possible that posix_spawn() is implemented as a library function calling fork/exec.

@sheredom I got curious and looked it up. Glibc implements posix_spawn() using the Linux clone() syscall with flags that make it behave a lot like vfork(). That should be a bit faster than calling fork() yourself, although I don't know how much.

I'm old enough to remember when Linux aliased vfork() to fork(). They said it was fast enough because Linux had COW memory. Looks like they changed their mind at some point.

Don't try to use vfork() directly. There be dragons.

@sheredom TIL searching $PATH for an executable is implemented in user space in glibc. It simply loops over each path component and tries to execve() each full path.

It looks like #! scripts are also handled that way. I thought the kernel did all this.

Sign in to participate in the conversation
Gamedev Mastodon

Mastodon server focused on game development and related topics.