When a C program calls system()
to run a Unix command, I know it's
possible to pass arguments to the command, and according to a
StackOverflow answer (from a very high-rep user), the system()
call
uses the shell to execute the
command.
It surprised me to see system("ls -lh >/dev/null 2>&1");
as an
example system()
call for a C program, since it looks like this is
using the same whitespace delimited "words" as the shell uses
interactively.
From my standpoint as a sysadmin, I'd like to understand what the
provisos and pitfalls are when a system()
call is going to be executed
from within a C program on some files or commands on my system.
Passing whitespace-containing filenames into a shell script is
very issue-prone;
are there similar issues when a C program is calling a command?
Or to make the point even blunter (though less exact): Is a C program written by a novice just as likely to break on whitespace-containing filenames as a shell script?
sh -c '...'
.system()
function uses the shell to execute the command, why are you surprised that it uses shell syntax? (2) As a sysadmin, you should try to minimize the use of thesystem()
function in programs on your system — don't use it, and discourage others from using it — especially if the program runs in a privileged context and/or builds its command string dynamically; especially if it builds its command string from user-supplied input. If you must use it, put a lot of thought and effort into validating the user input, to prevent code-injection-type attacks.system()
andexecve()
. Thanks.