#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/syscall.h>   /* For SYS_xxx definitions */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


int pfd[2];
void *thread_fn()
{
	pid_t tid = syscall(SYS_gettid);
	write(pfd[1], &tid, sizeof(tid));
	sleep(1000);
	return NULL;
}

int main()
{
	pid_t pid, tid, ppid = getpid();
	pthread_t t;

	if (pipe(pfd))
		return 1;

	pid = fork();
	if (pid < 0)
		return 1;
	if (pid == 0) {
		pthread_create(&t, NULL, thread_fn, (void *)(unsigned long)ppid);
		sleep(1000);
		return 0;
	}
	printf("fork: %d\n", pid);

	if (read(pfd[0], &tid, sizeof(tid)) != sizeof(tid))
		return 1;
	printf("thread: %d\n", tid);
	if (ptrace(PTRACE_ATTACH, tid, 0, 0))
		return 1;
	if (wait4(tid, NULL, __WALL, NULL) != tid)
		return 1;
	if (ptrace(PTRACE_ATTACH, pid, 0, 0))
		return 1;
	if (wait4(pid, NULL, __WALL, NULL) != pid)
		return 1;

	kill(pid, SIGKILL);

	*((int *)(0)) = 0xdead;

	return 0;
}