Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

[C], operative systems, fork, shared memory and semaphore

blubisblubis Member Posts: 2
Hello! I'm doing an exercise and this is the track:

The command line give 2 numbers: argv[1] = number of sons (n), argv[0] = variable (m)
the father generates n sons and create the shared memory segment. then wait until the sons end their job.
The sons work with a semaphore to modify the variable m that must be written and updated into the shared memory.
When the sons end, the father prints out the value contained in the variable m.

this is my code:

[CODE] #include
#include
#include
#include
#include
#include


int m; //shared variable

int main(int argc, char *argv[])
{
int segment_id;
int j;
int size = 4096;
sem_t *sem;
char *shared_memory;
pid_t pid;

/* build up the shared segment that will be shared among father and sons*/
segment_id = shmget( IPC_PRIVATE, size, S_IRUSR | S_IWUSR );

if ( segment_id < 0 ) { // DEBUG
printf("shared memory initilization failed
");
return 1;
}

/* initialize semaphore */
sem = sem_init(&sem, 0, 1 );

if ( !sem ) { // DEBUG
printf("error semaphore initilization
");
return 1;
}

/* father place the shared memory addres into his address scope*/
shared_memory = (char *)shmat( segment_id, NULL, 0 );

/* initialize m*/
m = atoi(argv[0]);

for (int x=0;x0) // father
wait(NULL); // wait for sons to end up
printf("valore: %s
", m); //prints out the final value of m

/* son place the shared memory addres into his address scope*/
if ( pid == 0 ) {
shared_memory = (char *)shmat( segment_id, NULL, 0 );

do {
sem_wait( &sem ); /* entry section*/

if (m%2 != 0) //modify variable m
m*=2;
else
m-=1;

// write the updated m into shared segment
sprintf(shared_memory, m);

sem_post( &sem ); /* exit section*/
} while(1);
}



/* father and sons deallocate shared segment*/
shmdt(shared_memory);

/* father remove semaphore and segment*/
if ( pid > 0 ) {
sem_delete(&sem);
shmctl(segment_id, IPC_RMID, 0 );
}

return 0;
}[/CODE]

now, my dubt are about how to place into the shared memory the variable m. Also I'd like to know what should I do to place the semaphore into the shared memory.
Basically, what's wrong with this code? :D

Thanks in advance,

B.
Sign In or Register to comment.