/* $Header:incr.c 12.0$ */
/* $ACIS:incr.c 12.0$ */
/* $Source: /ibm/acis/usr/sys/support/lib/RCS/incr.c,v $ */

#ifndef lint
static char *rcsid = "$Header:incr.c 12.0$";
#endif

/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1987
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* Increment a counter by arg2 or 1 if there is no arg2.
 * Write the new counter back to counterfile and to stdout.
 * Usage: a.out counterfile [ increment ] */

#include <sys/signal.h>
#include <stdio.h>
struct sigvec svhang, svint;
main(argc,argv)
int argc;
char *argv[];
{
	register char *argp = argv[1];
	FILE *cntin, *cntout;
	int incr = 1, counter;
	if(argc == 1){
		fprintf(stderr,"Usage:%s counter-file [incr-val]\n",argv[0]);
		exit(1);
	}
	if((cntin = fopen(argp, "r")) == NULL ) {
		fprintf(stderr,"Can't open %s for write\n",argp);
		exit(1);
	}
	if(argc >= 3) {
		if(sscanf(argv[2],"%d", &incr) != 1) {
			fprintf(stderr,"%s:bad increment\n",argv[0]);
			exit(1);
		}
	}
	if(fscanf(cntin,"%d", &counter) != 1){
		fprintf(stderr,"%s:bad counter value in %s\n",argv[0],argp);
		exit(1);
	}
	counter += incr;
		
		/* Ignore signals while writing counter. */
	svhang.sv_handler = SIG_IGN;
	svint.sv_handler = SIG_IGN;
	if(sigvec(SIGHUP, &svhang, 0) < 0 || sigvec(SIGINT, &svint, 0) < 0) {
		fprintf(stderr,"%s:bad return from sigvec\n",argv[0]);
		exit(1);
	}
	if((cntout = fopen(argp, "w")) == NULL) {
		fprintf(stderr,"Can't open %s for write\n",argp);
		exit(1);
	}
	fprintf(stdout,"%d\n", counter);
	fprintf(cntout,"%d\n", counter);
	exit(0);
}
