/*
 * simple util for x server connection status 
 *
 * cc checkx.c -lXm   kishan@hackorama.com June 2002
 */

#include <stdio.h>
#include <Xm/Xm.h>
#include <signal.h>
#include <limits.h>

#define OK 0
#define ERROR 1
#define FAIL 2
#define HANG 3

void checkit(char* disp, unsigned int time);
void onalarm();
void usage();
void redirect();
int check_errors();

const unsigned int timeout = 60;
const char err_file[MAXPATHLEN] = "/tmp/checkx.err";
int status = OK;

int main(int argc, char* argv[])
{
	if( argc < 2 )
		usage();
	else if ( argc == 2  )
		checkit(argv[1], timeout);
	else 
		checkit(argv[1], atoi(argv[2]));
	return status;
}

void checkit(char* disp, unsigned int time)
{
	Display *d;
	fprintf( stdout, "\n%s ", disp );

	redirect();

	signal(SIGALRM,onalarm);
    	alarm(time);

	if( (d=XOpenDisplay(disp)) == NULL ){
		if(check_errors() == 0) {
			fprintf(stdout, "ERROR\n\n");
			status = ERROR;
		} else {
			fprintf(stdout, "FAIL\n\n");
			status = FAIL;
		}
	}else{
		fprintf(stdout, "OK\n\n");
	}
}

void onalarm()
{
	fprintf(stdout, "HANG\n\n");
	status = HANG;
	exit(status);
}

/* return 0 if file is not empty */
int check_errors()
{
	FILE *fd = NULL;
	char s[5];
	fclose( stderr );
	fd = fopen(err_file, "r");
	if( fd != NULL ) {
		if ( fgets(s, sizeof(s), fd) != NULL ) {
			if( strlen(s) > 1 ) return 0;
		}
	}
	return 1;
}

void redirect()
{
	freopen(err_file, "w+", stderr);
}

void usage()
{
	fprintf(stdout, "\nUsage:\n\tcheckx display:x.x [time_out]\n\n" );
	fprintf(stdout, "\tdefault time_out is %d seconds \n\n", timeout);
	fprintf(stdout, "Eg:\n\n");
	fprintf(stdout, "\tcheckx tattoine:0.0\n");
	fprintf(stdout, "\tcheckx naboo:0.0 30\n\n");
	fprintf(stdout, "Returns:\n\n");
	fprintf(stdout, "\t%d OK \t- can connect\n", OK);
	fprintf(stdout, "\t%d ERROR\t- server returned error \n", ERROR);
	fprintf(stdout, "\t%d FAIL \t- failed to connect\n", FAIL);
	fprintf(stdout, "\t%d HANG \t- connection is hanging \n", HANG);
	fprintf(stdout, "\n\tIn case of ERROR, the error message can be\n");
	fprintf(stdout, "\tfound in the error log \"%s\".\n\n", err_file );
}


syntax highlighted by Code2HTML, v. 0.9