1EXAMPLE(7) libmawk manual EXAMPLE(7)
2
3
4
6 libmawk example - how to use the library
7
9 #include <libmawk.h>
10
11
13 Libmawk is a library that lets applications to embed awk scripts using
14 the code of the popular implementation mawk. The normal process is to
15 call libmawk_initialize() to set up a new mawk context (with script(s)
16 loaded), then in the main loop feed it using libmawk_append_input().
17 For "out of band" communication, the program may also call functions
18 implemented in awk and read (or modify) global variables of the awk
19 script. The hos tapplication usally will also bind some of its func‐
20 tions to the context using libmawk_register_function, which allows the
21 awk script to call the host applicaiton's functions directly as they
22 were awk builtins or user defined functions. After the main loop, the
23 application destroys the context freeing up all memory allocated for
24 the script(s).
25
26 One context is for one awk program. One awk program may consist of mul‐
27 tiple script files (just as with command line awk, with multiple -f
28 filename arguments). Libmawk is instance safe, the host application may
29 create multiple instances of contexts with the same or with different
30 set of awk scripts loaded. These contexts are totally separate, no
31 variables, functions or any sort of states are shared. However, the
32 host application may provide means of communication between those
33 scripts by custom functions or by copying variable contents between
34 them.
35
37 The following example application creates a single context to demon‐
38 strate all the above mentioned functionality.
39 #include <stdio.h>
40 #include <libmawk.h>
41
42 /*
43 Purpose: load and run a script using the command
44 line syntax of mawk but using a virtual
45 stdin buffer instead of the real stdin.
46 Run: ./app -f test.awk
47 */
48
49 int main(int argc, char **argv)
50 {
51 mawk_state_t *m;
52
53 /* init a context, execute BEGIN */
54 m = libmawk_initialize(argc, argv);
55 if (m == NULL) {
56 fprintf(stderr, "libmawk_initialize failed, exiting\n");
57 return 1;
58 }
59
60 /* feed in some data on the virtual stdin */
61 libmawk_append_input(m, "This is a\nmultiline test input\nfor the artificial input buffer.\n");
62
63 /* run the MAIN part of the script as long as
64 there's data in the buffer of the virtual stdin */
65 libmawk_run_main(m);
66
67 /* run END and free the context */
68 libmawk_uninitialize(m);
69
70 return 0;
71 }
72
73
74
75
76libmawk 2009-08-10 EXAMPLE(7)