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

╄→尐↘猪︶ㄣ 提交于 2019-12-22 09:45:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23752264/how-to-use-clone-to-make-parent-process-and-child-process-run-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!