How to create multiple child processes under the same parent in C? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to create multiple child processes under the same parent in C?

I am trying to create multiple child processes under the same parent. However I need the child processes to run concurrently, at the same time instead of sequentially.

10th Oct 2021, 12:46 PM
likage
likage - avatar
4 Answers
+ 3
// didn't test, but try this and let me know if it works or not #include <stdio.h> #include <unistd.h> static int childwork(); int main() { __pid_t ids[2]; #pragma omp parallel for for (int I = 0; I < 2; i++) { ids[I] = fork(); if (ids[I] == 0) { childwork(); } } return 0; } int childwork() { printf("PID: %d\n", getpid()); return 0; } // gcc -fopenmp main.c -o app // this should work as you want to fork the processes in parallel.
10th Oct 2021, 2:40 PM
Flash
+ 2
well, someone didn't like the answers. Could you care to explain, if I did something wrong in my code/answers, or did I break any SL rules?
10th Oct 2021, 2:47 PM
Flash
0
the chid processes are running in parallel (if you don’t wait for them in the parent process), only if they are spawned sequentially if used regular loops. If you want to spawn the child processes in parallel then use a parallel for loop.
10th Oct 2021, 2:26 PM
Flash
0
I know this is a bit much to ask, but any chance if you can show me in code? To be honest, upon googling online, I am no longer sure what is what and have gotten more confused even when I am already unsure about fork()
10th Oct 2021, 2:28 PM
likage
likage - avatar