How to use clone() to make parent process and child process run at the same time?

c, clone, linux, multithreading, system-calls

Solution

From `clone`

CLONE_VFORK (since Linux 2.2) If CLONE_VFORK is set, the execution of the calling process is suspended until the child releases its virtual memory resources via a call to execve(2) or _exit(2) (as with vfork(2)).

If CLONE_VFORK is not set, then both the calling process and the child are schedulable after the call, and an application should not rely on execution occurring in any particular order.

This means with `CLONE_VFORK`, it is supposed to wait until the child finishes or does an `exec`.

Since you run a function in the child, you don't need `exec`. Just leave out the `CLONE_VFORK`

clone(&do_something, (char *)stack + FIBER_STACK, CLONE_VM, 0);

and both the parent and child will run concurrently.

Problem

I'm new to linux. I want to make child process and parent process at the same time. But I have failed. Here is my code. Can anybody help me? ``` #define _GNU_SOURCE #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sched.h> #include <signal.h> #define FIBER_STACK 8192 void * stack; int do_something(){ int a = 0; while (a<10){ printf("pid : %d, a = %d\n", getpid(), a++); } exit(1); } int main() { void * stack; stack = malloc(FIBER_STACK); if(!stack) { printf("The stack failed\n"); exit(0); } int a = 0; if (c == 0) clone(&do_something, (char *)stack + FIBER_STACK, CLONE_VM|CLONE_VFORK, 0); while (a<10){ printf("pid : %d, a = %d\n", getpid(), a++); } free(stack); exit(1); } ``` I want them run in the same time, but the parent process wait until child process has finished.

Original source