harness.c 2.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * Copyright 2013, Michael Ellerman, IBM Corp.
 * Licensed under GPLv2.
 */

#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
14 15 16 17
#include <elf.h>
#include <fcntl.h>
#include <link.h>
#include <sys/stat.h>
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

#include "subunit.h"
#include "utils.h"

#define TIMEOUT		120
#define KILL_TIMEOUT	5


int run_test(int (test_function)(void), char *name)
{
	bool terminated;
	int rc, status;
	pid_t pid;

	/* Make sure output is flushed before forking */
	fflush(stdout);

	pid = fork();
	if (pid == 0) {
37
		setpgid(0, 0);
38 39 40 41 42 43
		exit(test_function());
	} else if (pid == -1) {
		perror("fork");
		return 1;
	}

44 45
	setpgid(pid, pid);

46 47 48 49 50 51 52 53 54 55 56 57 58 59
	/* Wake us up in timeout seconds */
	alarm(TIMEOUT);
	terminated = false;

wait:
	rc = waitpid(pid, &status, 0);
	if (rc == -1) {
		if (errno != EINTR) {
			printf("unknown error from waitpid\n");
			return 1;
		}

		if (terminated) {
			printf("!! force killing %s\n", name);
60
			kill(-pid, SIGKILL);
61 62 63
			return 1;
		} else {
			printf("!! killing %s\n", name);
64
			kill(-pid, SIGTERM);
65 66 67 68 69 70
			terminated = true;
			alarm(KILL_TIMEOUT);
			goto wait;
		}
	}

71 72 73
	/* Kill anything else in the process group that is still running */
	kill(-pid, SIGTERM);

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	if (WIFEXITED(status))
		status = WEXITSTATUS(status);
	else {
		if (WIFSIGNALED(status))
			printf("!! child died by signal %d\n", WTERMSIG(status));
		else
			printf("!! child died by unknown cause\n");

		status = 1; /* Signal or other */
	}

	return status;
}

static void alarm_handler(int signum)
{
	/* Jut wake us up from waitpid */
}

static struct sigaction alarm_action = {
	.sa_handler = alarm_handler,
};

int test_harness(int (test_function)(void), char *name)
{
	int rc;

	test_start(name);
	test_set_git_version(GIT_VERSION);

	if (sigaction(SIGALRM, &alarm_action, NULL)) {
		perror("sigaction");
		test_error(name);
		return 1;
	}

	rc = run_test(test_function, name);

112 113 114 115
	if (rc == MAGIC_SKIP_RETURN_VALUE)
		test_skip(name);
	else
		test_finish(name, rc);
116 117 118

	return rc;
}