Codebase list libmawk / debian/1.0.2-1 src / example_apps / 12_multi / app.c
debian/1.0.2-1

Tree @debian/1.0.2-1 (Download .tar.gz)

app.c @debian/1.0.2-1raw · history · blame

#include <stdio.h>
#include <libmawk.h>

/*
	Purpose: load the same script multiple times, running the instances
	         in parallel with different input. There's no race condition on
	         the output: scripts execution is strictly dictated by the
	         (single thread) app and both scripts are writing the same output
	         stream.
	Run: ./app -f test.awk
*/

int main(int argc, char **argv)
{
	mawk_state_t *m1, *m2;
	int n;

	/* init a context, execute BEGIN */
	m1 = libmawk_initialize(argc, argv);
	m2 = libmawk_initialize(argc, argv);
	if ((m1 == NULL) || (m2 == NULL)) {
		fprintf(stderr, "libmawk_initialize failed, exiting\n");
		return 1;
	}

	/* feed in some data on the virtual stdin */
	libmawk_append_input(m1, "[1] This is a\n[1] multiline test input\n[1] for the artificial input buffer.\n");
	libmawk_append_input(m2, "[2] This is a\n[2] multiline test input\n[2] for the artificial input buffer.\n");

	/* run the MAIN part of the script as long as there's data in the buffer of
	   the virtual stdin; this makes m1 process all available input before m2
	   starts processing its input. */
	libmawk_run_main(m1);
	libmawk_run_main(m2);

	/* run in parallel, record by record - inject only one record in the input
	   buffer before running the script */
	for(n = 0; n < 4; n++) {
		char tmp[32];

		sprintf(tmp, "[1] record %d\n", n);
		libmawk_append_input(m1, tmp);
		libmawk_run_main(m1);

		sprintf(tmp, "[2] record %d\n", n);
		libmawk_append_input(m2, tmp);
		libmawk_run_main(m2);
	}

	/* run END and free the context */
	libmawk_uninitialize(m1);
	libmawk_uninitialize(m2);

	return 0;
}