0

i am creating several child processes in my programming so i have decided to create an array of shared memory like so:

void makeSharedArr(int sharedId, int ** sharedArr, int numArgs)
{

    sharedId = shmget(IPC_PRIVATE, numArgs*sizeof(int), 0666 );
    if (sharedId < 0) 
    {
        perror("error allocating shared memory...exiting\n");
        exit(ERROR);
    }
    else 
    {
        write(1,"allocated memory...\n",20);
    }
    *sharedArr = (int *) shmat(sharedId, NULL, 0);
    if((long) sharedArr == -1) 
    {
        perror("error attaching the shared memory...exiting\n");
        exit(ERROR);
    }
    else
   {
        write(1,"attached the shared memory...\n",30);
   }

 }

after i operate some work the shared array i detach successfully but i am having trouble deleting the memory in my parent function:

 void parent(int *arr, int sharedId, int numArgs)
{
    //wait for all children
    while(wait(NULL) > 0) {/*..waiting..*/}

    // print array
    printf("array in parent: ");
    printArr(arr, numArgs);

    // detach and mark memory to be free 
    if(shmdt((void *) arr) == 0)
    {
        write(1, "memory block was detached...\n",29); 
    }
    else
    {
         write(1,"error detaching memory block...\n",32);
    }
    if(shmctl(sharedId, IPC_RMID, (struct shmid_ds *) NULL) == 0)
    {
         write(1, "memory block is now free...\n",28); 
    }
    else
    {  
        perror("error freeing memory\n");
        //write(1,"error freeing memory...\n",24);
    }
    // notify that parent is exiting
    printf("Parent exiting...\n");
 }
lest96
  • 59
  • 1
  • 2
  • 8
  • While thinking about how the function that called `makeSharedArr` will get the get the id returned by `shmget`, do a search for and read about *emulating pass by reference in c*. Or, simply, how to return values from functions. – Some programmer dude Apr 25 '16 at 14:05
  • And why are you using `write` to `STDOUT_FILENO`? Why not simply use `printf`, or `puts`? At least then you don't have to manually count the number of characters to print. – Some programmer dude Apr 25 '16 at 14:08
  • @JoachimPileborg wow thank you for that.. i did not catch that issue – lest96 Apr 25 '16 at 14:23
  • @JoachimPileborg also.. i was using write() because when using printf() it would print for every child process even though it was before the fork() call... i think it had to do with the system buffer not being flushed immediately when using printf() unlike write() that flushes the buffer instantly – lest96 Apr 25 '16 at 14:25
  • @JoachimPileborg i changed the write()'s to printf()'s and everything is running as expected thank yous – lest96 Apr 25 '16 at 16:54

0 Answers0