同时执行流程

Execute Process concurently

本文关键字:执行流      更新时间:2023-10-16

我的程序从user.then获取范围,然后创建3个进程并逐一执行但我希望所有进程同时运行。

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <sys/wait.h>
    void function();
    cin>>range;
cin>>process;
    int main() {
    int range = 1000;
    int i;
    int pid;
    int pid1;
    for(i = 0; i < ; i++) {
    pid1 = fork();
    }
    if(pid1==0) {
    pid = getpid();
    printf("The process id is: %dn", pid);
    function(range); 
    }
    else {
    wait(0); 
    }
    return 0;
    }

首先,正如其他人所提到的,您不是在分叉3个进程,而是在分叉8个进程。这样修复:

 for (i = 0; i < 3; ++i) {
     pid1 = fork();
     if (pid1 == 0) break;
 }

然后,所有4个进程并行运行。不过,根据function的作用,可能很难看到这一点——它可能完成得太快了。所以试试这个:

if (pid1 == 0) {
   printf("pid=%dn", getpid());
   sleep(5);
   printf("done sleep %dn", getpid());
} else {
   wait(0);
}

您应该打印出三个"pid=XX",然后延迟大约5秒,然后"完成睡眠XX"。