What is behind the "system" function in Perl?

I would have thought that he would open the shell, execute the parameter (shell command) and return the result to the scalar. But executing a system function in a Perl script is faster than a shell command. Will it invoke this command in C? If so, what's the difference between

rmdir foo 

and

 system('rmdir foo'); 
+4
source share
2 answers
  • The difference between the two is that the second will open the (fork) child process (which will be the rmdir command), while the first will make a direct Unix system call using the API without opening the process. Opening the child process is an expensive resource.

  • system() call always opens the child process for execution, BUT it can either open the shell, which, in turn, unscrews the desired program as its own child process (thus, receiving 2 child processes) or disconnect the program directly from the child process.

    The choice of when Perl opens a shell during a call to system() is outlined in perldoc -f system . A short (not 100% accurate) option:

    • If there is only one parameter for a system call, and the parameter is evaluated as a string containing shell metacharacters, the shell will branch out first.

    • If there is only one parameter and it does not have metacharacters; or there is a list of elements> 1 element, the program is deployed directly to bypass the shell.

Thus:

 system("rmdir foo"); # forks off rmdir command directly system("rmdir", "foo"); # forks off rmdir command directly system("rmdir foo > out.txt"); # forks off a shell because of ">" 
+11
source

Your system call starts a separate process, while Perl's own rmdir will call its own C function in the context of the Perl process. Both methods end up making the same system calls, but opening a new process is less efficient. *

Itโ€™s best to use Perl's own functions (like rmdir ): they are portable, and you donโ€™t have to worry about how to interpret shell exit codes, avoid metacharacters in file names to prevent security risks, etc.

* system will create an additional sh process if your command contains channels, I / O redirection, && , etc. This is not applicable in your case, but can make the system parameter even slower.

+5
source

Source: https://habr.com/ru/post/1307862/


All Articles