Difference between “system” and “exec” in Linux?

前端 未结 12 1945
天命终不由人
天命终不由人 2020-11-28 05:18

What is the difference between system and exec family commands? Especially I want to know which one of them creates child process to work?

12条回答
  •  孤街浪徒
    2020-11-28 05:55

    In general, "system" is so inefficient and you should not use it unless you have a small code. If you need to execute several programs in your process, you would better use fork&exec though you make it more complicated. Here is a list of differences between them:

    1- "system" command creates a copy of shell to execute your program. Every time you call a system, you create a copy of shell. So do not use it when you have lots of programs to execute inside your process.

    2- Specifically, if you want to execute system functions such as "mv", "mkdir", it would be better to use routines such as mkdir(), unlink() or remove() instead of executing them through "system("rm ....") or system("mkdir ....")".

    3- Since system calls shell to execute your desired program, you may have some user permission problems. For example, someone may crack your code and execute something else instead of the program you intended to execute through system command.

    For more information, you may read chapter 11 of this book: "UNIX Systems Programming" by David Curry.

提交回复
热议问题