Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #define NPROCS 7 /*Number of processes to be created*/
- #define MSGLEN 9 /*Length of messages sent to each process*/
- int main(){
- int fd[NPROCS][2], i, myID = 0, parent, rng, j, num;
- char msg[MSGLEN];
- for(i = 0; i < NPROCS; i++){ /*Create pipes*/
- if(pipe(fd[i]) == -1){
- perror("Piping error");
- exit(-1);
- }
- }
- for(i = 1; i < NPROCS; i++){ /*Create processes*/
- switch(parent = fork()){
- case -1:
- perror("Forking error");
- exit(-1);
- case 0:
- myID = i;
- }
- if(parent){
- break;
- }
- }
- /*COMMON CODE*/
- close(fd[myID][1]); /*Close current process's write end to pipe*/
- for(i = 0; i < NPROCS; i++){ /*Close all read ends from other processes*/
- if(i != myID){
- close(fd[i][0]);
- }
- }
- sprintf(msg, "process%d", myID);
- int count = 0;
- srand(71913173*myID);
- rng = RAND_MAX/NPROCS; /*Generate random numbers, write to 13 random processes*/
- rng *= NPROCS;
- for(i = 0; i < 13; i++){
- do{
- num = rand();
- j = num % NPROCS;
- } while(num >= rng || myID==j);
- count++;
- printf("myID: %d, j: %d, count: %d\n", myID, j, count);
- if(write(fd[j][1], msg, MSGLEN) != MSGLEN){
- perror("Write error");
- exit(-1);
- }
- }
- for(i = 0; i < NPROCS; i++){ /*Close all write ends*/
- if(i != myID){
- close(fd[i][1]);
- }
- }
- msg[MSGLEN] = '\0';
- while(read(fd[myID][0], msg, MSGLEN) == MSGLEN){
- printf("process%d has received a message from %s\n", myID, msg);
- }
- close(fd[myID][0]);
- exit(0);
- }
Add Comment
Please, Sign In to add comment