/* distributed under the terms of the GPL-2 */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>

int proc_exist(int pid)
{
	int ret = kill(pid, 0);

	if (ret == 0) /* process exists */
		return 1;

	if (errno == EPERM) /* process exists but we may not signal it */
		return 1;

	if (errno == ESRCH)
		return 0; /* process does not exist */

	perror("kill");
	return 0;
}

int main(int argc, char **argv)
{
	if (argc < 2) {
		printf("Usage: wait_on_pid PID\n");
		return EXIT_FAILURE;
	}
	int pid=atoi(argv[1]);

	if (!proc_exist(pid)) {
		perror("wait_on_pid");
		return 1;
	}
	if (pid == 0) {
		printf("Waiting for pid 0 is not useful.\n");
		return EXIT_FAILURE;
	}

	if (pid == 1)
		printf("Waiting for init (pid 1) is not useful, still doing it.\n");

	while (proc_exist(pid)) {
		usleep(500*1000);
	}
	return EXIT_SUCCESS;
}

