C Programming Tutorial

 
 
 
 
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include \"headsem.h\"
#include \"headfork.h\"

main()
{
    int max,min,np,a[10];
    int *lock1,*finalmax,*finalmin;
    int id,n,i,sid1,sid2,sid3;

    sid1=shmget(IPC_PRIVATE,10,0666|IPC_CREAT);
    lock1=(int *)shmat(sid1,0,0);

    sid2=shmget(IPC_PRIVATE,10,0666|IPC_CREAT);
    finalmax=(int *)shmat(sid2,0,0);

    sid3=shmget(IPC_PRIVATE,10,0666|IPC_CREAT);
    finalmin=(int *)shmat(sid3,0,0);

    *finalmax=0;

    printf(\"Enter the size of array :\");
    scanf(\"%d\",&n);

    printf(\"Enter the array elements :\");
    for(i=0;i<n;i++)
        scanf(\"%d\",&a[i]);

    printf(\"Enter the no.of proc :\");
    scanf(\"%d\",&np);

    lock_init(lock1);

    id=p_fork(np);

    max=a[0];    
    min=a[0];

    for(i=id;i<n;i+=np)
    {
        if(a[i]>max)
            max=a[i];
        if(a[i]<min)
            min=a[i];
    }

    locksem(lock1);

    *finalmin=min;
    if(min<*finalmin)
        *finalmin=min;
    unlock(lock1);

    locksem(lock1);
    if(max > *finalmax)
        *finalmax=max;
    unlock(lock1);

    p_join(np,id);
    printf(\"minimum : %d\",*finalmin);
    printf(\"maximum : %d\",*finalmax);
}

 
 
Didn't find what you were looking for? Find more on PROGRAM FOR MAX and MIN OF ARRAY USING SPIN LOCK