/*Code open-sourced by http://codejar-lab.in This is only for study purpose only and if you found any error use own logic to correct it so dont comment error. */ #include<stdio.h> #include<sys/ipc.h> #include<sys/wait.h> #include<sys/shm.h> int FFork(int iProcess) { int iCount; int PId; for (iCount=1; iCount<iProcess; iCount++) { PId = fork(); if (PId == 0) return(iCount); } return(0); } void FJoin(int nProc,int PId) { int iCount; if (PId == 0) for (iCount=1; iCount<nProc; iCount++) wait(0); else exit(0); } void *sshared (int size, int *shmid) { *shmid=shmget ( IPC_PRIVATE, size,0666 | IPC_CREAT); if (*shmid < 0) { printf("Error, cannot share memory"); exit(0); } return shmat(*shmid,0,0); } void cleanup_memory(int *shmid) { struct shmid_ds *buf; if (shmctl(*shmid,IPC_RMID,buf) !=0) { printf("Error, cannot free memory"); exit(0); } } int main() { int a[10]={1,2, 3,4, 5,6, 7,8, 9,10}; int pid,j; int *sum,shmid; sum=(int *)sshared(sizeof(int)*5,&shmid); pid=FFork(5); printf("Current process : %d" ,pid); for(j=pid;j<pid+2;j++) { sum[pid] = sum[pid] + a[j] ; } FJoin(5,pid); printf("[1] = %d\n", sum [0] ); printf("[2] = %d\n", sum [1] ); printf("[3] = %d\n", sum [2] ); printf("[4] = %d\n", sum [3] ); printf("[5] = %d\n", sum [4] ); printf("Total sum = %d\n", sum[0] + sum[1] + sum[2] + sum[3] + sum[4]); }How to run it?
$gcc file.c
$./a.out