hi friends
I've a code to compute integral with area function in code. I used Fork, and for returned values I must use shared memory.
now I need to embed a semaphore in my code to control the critical area(here is shared memory).
I don't know how to embed semaphore in it.
Here is the code:

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

int area(int a,int b,int H) {return (((a*a)+(b*b))*H)/2;}
sem_t sem;
main()
{
    int *value;
    pid_t pid;
    int i;
    int status;
    int result=0;
    int pids[10];
    int shmid;
    key_t key;
    key=ftok("prog.c",0);
    shmid=shmget(key,1024,0644|IPC_CREAT);
    value=shmat(shmid,(void *)0,0);
    if(value==(int *)(-1))
        perror("shmat");
    if(sem_init(&sem,0,0)==-1)
        perror("Semaphore initialize failed");
    for(i=0;i<=9;i++)
    {

        pid=fork();
        if(pid==0)
        {

            *value=area(i,i+1,1);
            printf("I'm child: %d -> Value: %d\n",i,*value);
            exit (EXIT_SUCCESS);
        }
        else if(pid>=1) pids[i]=pid;
    }
        for(i=0;i<=9;i++)
    {
        wait(&status);
        if(WIFEXITED(status))
        {
            if(pids[i]>=1)
            {
                result+=*value;
                printf("I'm Parent: %d -> Value Returned: %d\n",i,*value);
            }
        }
    }
    printf("result : %d\n",result);
    shmdt(value);
}

I appreciate any help.
good luck.

To share the semaphore, it has to be in the shared memory space. Therefore, you'll want to redefine the semaphore variable as a pointer, then point it somewhere in the shared memory space that isn't being used, then initialize it.

This article has been dead for over six months. Start a new discussion instead.