Warm tip: This article is reproduced from serverfault.com, please click

Printing a matrix containing processes in C

发布于 2020-12-22 20:14:08

I wrote a C program in which a 5x5 matrix generates a process by forking in each cell. The problem is that, if I try to print PIDs, it doesn't print the matrix correctly. Here the code:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define ROW 5
#define COL 5

int main (){

pid_t pid_matrix[ROW][COL];
  
for (size_t row = 0; row < ROW; ++row){
    for (size_t col = 0; col < COL; ++col){
        pid_matrix[row][col] = fork();
        if (pid_matrix[row][col] == -1){
            // Error! 
        }
        else if (pid_matrix[row][col] == 0){
            printf("\t%d", getpid());
            exit(EXIT_SUCCESS);  
        } 
    }
    printf("\n");
}

    return 0;
}

Actually my code prints this:

    14233
    14234   14235   14236   14237   14238   14239   14240
    14241   14242   14243   14244   14245
    14246   14247   14248   14249   14250
    14251   14252   14253   14254
    14256   14255   14257

I tried to add a sleep after forking, but the result was this:

    14158   14159   14162   14163
    14164   14165   14166   14167   14168
    14169   14170   14171   14175   14176
    14177   14178   14179   14180   14181
    14182   14183   14184   14185   14186
    14187

Of course, my wanted code would print something like:

    14158   14159   14162   14163   14164
    14165   14166   14167   14168   14169
    14170   14171   14172   14173   14174
    14175   14176   14177   14178   14179
    14182   14183   14184   14185   14186
    

What am I doing wrong? What do I need to correct in my code to print the matrix correctly?

Questioner
Chiara Tumminelli
Viewed
0
tstanisl 2020-12-23 04:28:57

Just add wait() after processing loop body in parent process. This will assure that the child process has finished before processing another entry in the matrix.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

#define ROW 5
#define COL 5

int main (){

pid_t pid_matrix[ROW][COL];
  
for (size_t row = 0; row < ROW; ++row){
    for (size_t col = 0; col < COL; ++col){
        pid_matrix[row][col] = fork();
        if (pid_matrix[row][col] == -1){
            // Error! 
        }
        else if (pid_matrix[row][col] == 0){
            printf("\t%d", getpid());
            exit(EXIT_SUCCESS);  
        } 
        wait(NULL);
    }
    printf("\n");
}

    return 0;
}