to system() or fork()/exec()?

前端 未结 4 1276
不思量自难忘°
不思量自难忘° 2020-12-16 15:25

There appear to be two common ways of running an external executable from C in unix, the

system()

call and

pid = fork()
sw         


        
相关标签:
4条回答
  • 2020-12-16 15:35

    system() will type out the command and execute it like a user would have typed out. i mostly saw it like system("pause"); system("cls");

    But if you need to control the child process, you want to fork.

    0 讨论(0)
  • 2020-12-16 15:36

    Going via system() additionally invokes a shell process, which might not be what you want.

    Also the calling process is notified only when such shell dies not when the actual process run by the shell died.

    0 讨论(0)
  • 2020-12-16 15:38

    fork() creates a new process. If you don't need to do that, just use system() (or popen()). You might want a second process to achieve parallelism, or for finer-grained control over the job, but often you just don't care for that if the job is meant to be synchronous.

    On the other hand, I find that 95% of uses of system() are unnecessary or would somehow be better off done another way (e.g. using zlib instead of system("gzip")). So maybe the best answer is to use neither!

    0 讨论(0)
  • 2020-12-16 15:59

    system executes a command-interpreter, i.e. a shell, which (a) is slower than a direct fork/exec, (b) may behave differently on different systems and (c) is a potential security hazard if you pass it a string from an untrusted source. Also, system waits for the child process to exit, while you might want it to run concurrently with the parent process.

    More in general, the low-level fork/exec gives you additional control: before or in between the two operations, you might want to chdir, open pipes, close file descriptors, set up shared memory, etc.

    (By different systems, I don't mean Windows vs. Unix (as Windows doesn't even have fork): I'm talking Red Hat Linux vs. Ubuntu. The former uses Bash to execute what is passed to system, the latter a lightweight POSIX-compatible shell.)

    0 讨论(0)
提交回复
热议问题