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

前端 未结 12 1890
天命终不由人
天命终不由人 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:38

    system() will invoke your systems default command shell, which will execute the command string passed as an argument, that itself may or may not create further processes, that would depend on the command and the system. Either way, at least a command shell process will be created.

    With system() you can invoke any command, whereas with exec(), you can only invoke an executable file. Shell scripts and batch files must be executed by the command shell.

    Basically they are entirely different used for different purposes. Moreover exec() replaces the calling process, and does not return. A more useful comparison would be between system() and spawn(). While system may be simpler to invoke, it returns a value that tells you whether the command shell was invoked, and tells you nothing about the success of the command itself. With spawn() you can get the process's exit code; by convention non-zero is used to indicate error conditions. Like exec() spawn() must invoke an executable, not a shell script or built-in command.

提交回复
热议问题