gpt4 book ai didi

c - 如何使用clone()让父进程和子进程同时运行?

转载 作者:太空狗 更新时间:2023-10-29 11:14:13 25 4
gpt4 key购买 nike

我是 Linux 新手。我想同时制作子进程和父进程。但是我失败了。这是我的代码。谁能帮帮我?

#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);
}

我希望它们同时运行,但父进程要等到子进程完成。

最佳答案

来自 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.

这意味着对于 CLONE_VFORK,它应该等到 child 完成或执行 exec

因为你在子进程中运行一个函数,你不需要exec。只需省略 CLONE_VFORK

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

而且父子会同时运行。

关于c - 如何使用clone()让父进程和子进程同时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23752264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com