gawk: Using Internal File Ops
16.6.3 Integrating the Extensions
---------------------------------
Now that the code is written, it must be possible to add it at runtime
to the running 'gawk' interpreter. First, the code must be compiled.
Assuming that the functions are in a file named 'filefuncs.c', and IDIR
is the location of the 'gawkapi.h' header file, the following steps(1)
create a GNU/Linux shared library:
$ gcc -fPIC -shared -DHAVE_CONFIG_H -c -O -g -IIDIR filefuncs.c
$ gcc -o filefuncs.so -shared filefuncs.o
Once the library exists, it is loaded by using the '@load' keyword:
# file testff.awk
@load "filefuncs"
BEGIN {
"pwd" | getline curdir # save current directory
close("pwd")
chdir("/tmp")
system("pwd") # test it
chdir(curdir) # go back
print "Info for testff.awk"
ret = stat("testff.awk", data)
print "ret =", ret
for (i in data)
printf "data[\"%s\"] = %s\n", i, data[i]
print "testff.awk modified:",
strftime("%m %d %Y %H:%M:%S", data["mtime"])
print "\nInfo for JUNK"
ret = stat("JUNK", data)
print "ret =", ret
for (i in data)
printf "data[\"%s\"] = %s\n", i, data[i]
print "JUNK modified:", strftime("%m %d %Y %H:%M:%S", data["mtime"])
}
The 'AWKLIBPATH' environment variable tells 'gawk' where to find
extensions (Finding Extensions). We set it to the current
directory and run the program:
$ AWKLIBPATH=$PWD gawk -f testff.awk
-| /tmp
-| Info for testff.awk
-| ret = 0
-| data["blksize"] = 4096
-| data["devbsize"] = 512
-| data["mtime"] = 1412004710
-| data["mode"] = 33204
-| data["type"] = file
-| data["dev"] = 2053
-| data["gid"] = 1000
-| data["ino"] = 10358899
-| data["ctime"] = 1412004710
-| data["blocks"] = 8
-| data["nlink"] = 1
-| data["name"] = testff.awk
-| data["atime"] = 1412004716
-| data["pmode"] = -rw-rw-r--
-| data["size"] = 666
-| data["uid"] = 1000
-| testff.awk modified: 09 29 2014 18:31:50
-|
-| Info for JUNK
-| ret = -1
-| JUNK modified: 01 01 1970 02:00:00
---------- Footnotes ----------
(1) In practice, you would probably want to use the GNU Autotools
(Automake, Autoconf, Libtool, and 'gettext') to configure and build your
libraries. Instructions for doing so are beyond the scope of this Info
file. gawkextlib for Internet links to the tools.