Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

264 Process Control Chapter 8


instead of needing to know that the program is really anawkscript that we
would otherwise have to execute as
awk -f awkexampleoptional-arguments


  1. Interpreter scripts provide an efficiency gain. Consider the previous example
    again. Wecould still hide that the program is anawkscript, by wrapping it in a
    shell script:
    awk ’BEGIN {
    for (i = 0; i < ARGC; i++)
    printf "ARGV[%d] = %s\n", i, ARGV[i]
    exit
    }’ $*
    The problem with this solution is that morework is required. First, the shell
    reads the command and tries toexeclpthe filename. Because the shell script is
    an executable file but isn’t a machine executable, an error is returned and
    execlpassumes that the file is a shell script (which it is). Then/bin/shis
    executed with the pathname of the shell script as its argument. The shell
    correctly runs our script, but to run theawkprogram, the shell does afork,
    exec,and wait.Thus there is moreoverhead involved in replacing an
    interpreter script with a shell script.

  2. Interpreter scripts let us write shell scripts using shells other than/bin/sh.
    When it finds an executable file that isn’t a machine executable,execlphas to
    choose a shell to invoke, and it always uses/bin/sh.Using an interpreter
    script, however, we can simply write
    #!/bin/csh
    (C shell script follows in the interpreter file)
    Again, we could wrap all of this in a/bin/shscript (that invokes the C shell),
    as we described earlier,but moreoverhead is required.
    None of this would work as we’ve shown here if the three shells andawkdidn’t use the
    pound sign as their comment character.


8.13 systemFunction


It is convenient to execute a command string from within a program. For example,
assume that we want to put a time-and-date stamp into a certain file.We could use the
functions described in Section 6.10 to do this: calltimeto get the current calendar time,
then calllocaltimeto convert it to a broken-down time, then callstrftimeto format
the result, and finally write the result to the file. It is much easier,however, to say
system("date > file");
ISO C defines thesystemfunction, but its operation is strongly system dependent.
POSIX.1 includes thesysteminterface, expanding on the ISO C definition to describe
its behavior in a POSIX environment.
Free download pdf