/*
 * sig_reparent.c: race a killing signal against exit() of parent process.
 * 
 * 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 grandchildpid;
	int raced;
	int reparented;
	int parentdone;
	int error;
};

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

	stp->grandchildpid = 0;
	stp->raced = 0;
	stp->reparented = 0;
	stp->parentdone = 0;
	stp->error = 0;
	if ((pid = fork()) == 0) {
		sched_setaffinity(0, sizeof(childcpuset), &childcpuset);
		if ((grandchildpid = fork()) == 0) {
			stp->grandchildpid = getpid();
			while (getppid() == pid) {
				sched_yield();
			}
			stp->reparented = 1;
			while (!stp->parentdone) {
				sched_yield();
			}
			_exit(0);
		}
		if (grandchildpid == -1) {
			perror("fork");
			stp->error = 1;
			exit(-1);
		}
		while (stp->grandchildpid == 0) {
			sched_yield();
		}
		spindelay(us2spindelay(50));
		stp->raced = 1;
		_exit(0);
	}
	while (stp->grandchildpid == 0) continue;
	spindelay(parentspin);
	if (kill(pid, SIGINT) != 0) {
		perror("kill");
		exit(-1);
	}
	stp->parentdone = 1;
	if (stp->error) {
		exit(-1);
	}
	if (!stp->raced) {
		retval = STEAMROLLER_EARLY;
	} else if (!stp->reparented) {
		retval = STEAMROLLER_RACED;
	} else {
		retval = STEAMROLLER_LATE;
	}
	return retval;
}

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);
}
