简体   繁体   中英

Printing an array in order with fork()

i'm trying to print an array with help of fork, where every element will be printed by a seperate child process.

void printArray_fork(int *p_array, int length){
    int i;

    pid_t pid;
    for(i = 0; i<length;i++){
        /* Create children procs */
        pid = fork();
        if(pid==0){
            break;
        }
    }

    if(pid == 0) {
            printf( "My process ID : %d value: %d\n",getpid(),*(p_array + i));
    }
}

Now the issue is that I want it also to be in order (ascending or descending, doesnt matter) How would I do that?

Here a little modification of your code to print in order.

  /* Create children procs */
     pid = fork();
     wait();

As suggested above, all you need is to use wait for the next child process to be created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM