Skip to content

Instantly share code, notes, and snippets.

@513ry
Last active February 18, 2022 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 513ry/4d6935b4b64a6662c0b6513cb1f6bf66 to your computer and use it in GitHub Desktop.
Save 513ry/4d6935b4b64a6662c0b6513cb1f6bf66 to your computer and use it in GitHub Desktop.
2D process control
#include <errno.h>
#include <unistd.h>
#include <sys/types.h> /* used by pid_t */
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
/* How many times program returns to the parent to run the new branch of
processes
*/
#define YDEPTH 2
void spawn(int n, int np, pid_t ppid, int y);
/* Main Procedure ****************************************************/
int
main (void) {
int tree[YDEPTH], rv;
pid_t ppid;
// Set the process tree branches
tree[0] = tree[1] = 3;
// Top parent pid (host process)
ppid = getpid();
// Fork all child processes
for (int depth = 0; depth < YDEPTH; ++depth) {
printf ("PARENT %d: Spawinng a new branch with depth %i\n", getpid(), tree[depth]);
spawn(tree[depth], tree[depth], ppid, depth);
printf("Check back to parrent\n");
}
printf("Parent is free now\n");
// Wait the top processes
for (int index = 0; index < YDEPTH; ++index) {
wait(&rv);
printf("Parent process get RV %i\n", WEXITSTATUS(rv));
}
// Standard exit
printf("*DONE*\n");
return EXIT_SUCCESS;
}
/* Spawn procedure will fork n children processes */
// TODO: Add semephores
void
spawn(int n, int np, pid_t ppid, int y) {
// pid_t chlid_pid;
pid_t pid;
int rv = -1;
if (np) {
switch (pid = fork()) {
case -1: /* FORK RETURN AN ERROR (see `man 2 fork`, ERRORS section) */
perror("Fork failed!\n"); /* something went wrong */
exit(EXIT_FAILURE); /* parent exits */
case 0: /* PID RETURNED IN THE CHILD */
printf("> Z CHILD %d: My parent's PID = %d\n", getpid(), getppid());
spawn (n, np - 1, ppid, y);
// Run process job
int jobs_done = 2;
while (jobs_done) {
sleep(1);
printf("%i.%i> Hello, my pid is %i, and my parent's is %i\n",
np, y, getpid(), getppid());
--jobs_done;
}
printf("%d IS DONE (%i/%i/%i)\n", getpid(), y, n, np);
if (np != 1) {
printf("Parent %i waiting for child to exit\n", getpid());
wait(&rv);
sleep(0 );
printf("RV = %i\n", WEXITSTATUS(rv));
}
printf("%d EXIT\n", getpid());
exit(10);
default:
printf ("> SKIP IN %i: My parent's PID = %i; My childrens pid = %i\n",
getpid(), getppid(), pid);
}
}
printf("\n%d GET SOMETHING TO DO\n", getpid());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment