Pipes between child processes in C

后端 未结 4 2029
旧时难觅i
旧时难觅i 2021-01-03 17:24

I\'ve seen this question before, but still a bit confused: how would I create communication between child processes of the same parent? All I\'m trying to do at the moment i

4条回答
  •  无人及你
    2021-01-03 17:59

    In a simplified non-exec case, you should do something like.

    #define nproc 17
    
    int pipes[nproc - 1][2];
    int pids[nproc];
    
    int i;
    for( i = 0; i < nproc - 1; i++ ) {
        pipe( pipes[i] );
    }
    
    int rank;
    for( rank = 0; rank < nproc; rank++ ) {
        pids[rank] = fork();
        if( !pids[rank] ) {
            if( rank == 0 ) {
                write( pipe[rank][1], /* your message */ );
            }
    
            read( pipe[rank-1][0], /* read the message somewhere*/ );
    
            if( rank < nproc - 1 ) {
                write( pipe[rank][1], /* write the message to the next child process*/ );
            } else {
                // Here print the received message (it's already received above)
            }
        }
    }
    
    for( rank = 0; rank < nproc; ++rank ) {
        wait( pids[rank] );
    }
    

提交回复
热议问题