Skip to content

Instantly share code, notes, and snippets.

@michaellee8
Created September 27, 2018 10:26
Show Gist options
  • Save michaellee8/cae26ddb014a45b5fc38914e7ca793a9 to your computer and use it in GitHub Desktop.
Save michaellee8/cae26ddb014a45b5fc38914e7ca793a9 to your computer and use it in GitHub Desktop.
Play with c fork and pstree
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
void create_process(int current_level)
{
int parent = (int)getpid();
int child = (int)fork();
// printf("ps_forked %d %d\n", current_level,(int)getpid());
if (child > 0)
{
// I am parent
int status;
waitpid(child, &status, 0);
}
else
{
// I am child
if (current_level > 0)
{
create_process(current_level - 1);
}
else
{
// I am the last child, exec pstree now.
char bottom_str[100];
sprintf(bottom_str, "%d", (int)getpid());
execlp("pstree", "pstree", "-s", bottom_str, NULL);
}
}
}
int main(int argc, char *argv[])
{
int total_level;
sscanf(argv[1], "%d", &total_level);
create_process(total_level - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment