#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/wait.h>


int main(int argc, char *argv[]) {
pid_t chpid, pspid;
char pid_buf[10];
int child_status;

if ((chpid = fork()) == -1) {
	perror("cannot fork");
	exit(1);
}
else if (chpid == 0) { /* child here */
	/* Wait for 5 sec */
	sleep(5);
	return 1;
}
/* Only parent continues here */

/* Ask ps to print child status - child is still alive! */
sprintf(pid_buf, "%ld", (long)chpid);
if ((pspid = fork()) == -1) {
	perror("cannot fork for ps");
}
else if (pspid == 0) {
	execl("/bin/ps", "ps", "-lp", pid_buf, NULL);
	perror("cannot exec /bin/ps");
	exit(2);

}
/* wait for ps child only! */
waitpid(pspid, NULL, 0);

sleep(8); /* wait for child to finish */

/* Do not collect child process exit code via wait, ask ps to
   report its status */
if ((pspid = fork()) == -1) {
	perror("cannot fork for ps");
}
else if (pspid == 0) {
	execl("/bin/ps", "ps", "-lp", pid_buf, NULL);
	perror("cannot exec /bin/ps");
	exit(2);

}
/* wait for ps child only! */
waitpid(pspid, NULL, 0);

if (waitpid(chpid, &child_status, 0) != chpid) {
	perror("cannot collect child status:");
}
else
	printf("child status: %d\n", child_status);

return 0;
}
