Time waste of execv() and fork()

前端 未结 6 912
青春惊慌失措
青春惊慌失措 2020-12-16 09:30

I am currently learning about fork() and execv() and I had a question regarding the efficiency of the combination.

I was shown the followin

6条回答
  •  孤城傲影
    2020-12-16 09:38

    It's not that expensive (relatively to spawning a process directly), especially with copy-on-write forks like you find in Linux , and it's kind of elegant for:

    1. when you really just want to fork off a clone of the current process (I find this to be very useful for testing)
    2. for when you need to do something just before loading the new executable (redirect filedescriptors, play with signal masks/dispositions, uids, etc.)

    POSIX now has posix_spawn that effectively allows you to combine fork/and-exec (possibly more efficiently than fork+exec; if it is more efficient, it'll usually be implemented through some cheaper but less robust fork (clone/vfork) followed by exec), but the way it achieves #2 is through a ton of relatively messy options, which can never be as complete and powerful and clean as just allowing you to run arbitrary code just before the new process image is loaded.

提交回复
热议问题