-3

私のプログラムはuser.thenから範囲を取り、3つのプロセスを作成して1つずつ実行しますが、すべてのプロセスを同時に実行したいです。

    #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: %d\n", pid);
    function(range); 
    }
    else {
    wait(0); 
    }
    return 0;
    }
4

1 に答える 1

1

First, as others have mentioned, you are not forking 3 processes, you are forking 8. Fix that like this:

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

Then, all 4 processes are running in parallel. Depending on what function does, it may be hard to see this, though - it may finish too quickly. So try this:

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

You should three printouts of "pid=XX", then a delay of about 5 seconds, then "done sleep XX".

于 2013-07-15T13:58:25.853 に答える