/*
 * sig_exit.c: race a killing signal against exit().
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Copyright (C) IBM Corporation, 2005
 *
 * Author: Paul E. McKenney <paulmck@us.ibm.com>
 */

#include "steamroller.h"

struct sig_test_ctrl {
	int startflag;
	int raced;
};

int test_sig_dfl__exit(void *p, int parentspin, long childcpuset)
{
	int i;
	int pid;
	int status;
	struct sig_test_ctrl *stp = (struct sig_test_ctrl *)p;

	stp->startflag = 0;
	stp->raced = 0;
	if ((pid = fork()) == 0) {
		sched_setaffinity(0, sizeof(childcpuset), &childcpuset);
		stp->startflag = 1;
		spindelay(us2spindelay(100));
		stp->raced = 1;
		_exit(0);
	}
	if (pid == -1) {
		perror("fork");
		exit(-1);
	}
	while (stp->startflag == 0) continue;
	spindelay(parentspin);
	if (waitpid(pid, &status, WNOHANG) != 0) {
		return STEAMROLLER_LATE;
	} else {
		if (kill(pid, SIGINT) != 0) {
			perror("kill");
			exit(-1);
		}
		wait(&status);
		if (WIFEXITED(status)) {
			return STEAMROLLER_RACED;
		} else if (WIFSIGNALED(status)) {
			if (stp->raced == 0) {
				return STEAMROLLER_EARLY;
			} else {
				return STEAMROLLER_RACED;
			}
		} else {
			fprintf(stderr,
				"strange exit after signal%d\n", status);
			exit(-1);
		}
	}
}

int main(int argc, char *argv[])
{
	long childcpuset;
	void *p;

	childcpuset = steamroller_init(argc, argv);
	p = (int *)mapmem(sizeof(struct sig_test_ctrl), -1);
	search_and_steamroller(test_sig_dfl__exit, p, childcpuset);
}
