如何使用clone()使父进程和子进程同时运行? [英] How to use clone() to make parent process and child process run at the same time?

查看:342
本文介绍了如何使用clone()使父进程和子进程同时运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Linux新手.我想同时制作子流程和父流程.但是我失败了.这是我的代码.有人可以帮我吗?

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.

推荐答案

来自 clone

CLONE_VFORK (自Linux 2.2起)
如果设置了CLONE_VFORK,则执行调用过程是 暂停,直到孩子释放其虚拟内存 通过调用execve(2)或_exit(2)获得资源(与 vfork(2)).

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)).

如果未设置CLONE_VFORK,则调用过程和 通话后,该孩子可以安排日程,并申请 不应该依赖于任何特定情况下发生的执行 订单.

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.

这意味着对于CLONE_VFORK,应该等到孩子完成或完成exec.

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

由于在子代中运行函数,因此不需要exec.只需删除CLONE_VFORK

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.

这篇关于如何使用clone()使父进程和子进程同时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆