1

I have a problem with shared memory and processes. I attach an area to the shared memory, I make a child proccess but when I try to modify the shared memory area in the father process I only get segmentation fault, it just can be modified in the child.

.h

struct infoHeaders {
char words[512];
int num [512];
};
int idShMem; 
struct infoHeaders * ptrInfo;

.cc

idShMem = shmget( 123456, sizeof(struct infoHeaders), 0700 | IPC_CREAT ); 
ptrInfo = (infoHeaders *) shmat( idShMem, NULL, 0 );

if (!fork()) {
        sem.wait();
        exit(0);
}
else {
    ptrInfo->num[0] = 1; //Segmentation Fault
    sem.signal();
}

}

sem is an object of a Semaphore class, I tested it and it has no problems.

Any ideas ?

3
  • 2
    What is the value of ptrInfo? You don't seem to check for an error return from shmat(). Does your code behave differently if you try to use ptrInfo without calling fork()? Commented May 10, 2015 at 7:51
  • ptrInfo is just a pointer to the struct infoHeader. It adquires a value when I call shmat(). I don't know how to check for an error i shmat(). If I don't call fork() segmentation fault still remains, it seems that I can only modify the shared memory area in a child process. Commented May 10, 2015 at 7:58
  • Read the manpage to find out how errors are signaled. That said, is the fork() call actually relevant? In any case, please state which Unix system you are using and extract a minimal but complete example. See also stackoverflow.com/help/how-to-ask Commented May 10, 2015 at 8:01

1 Answer 1

1

Check the return value of shmget (which you are storing in idShMem). It is possible for the call to fail. If it is negative then you are never successfully allocating the memory in the first place. If idShMem is negative, that is your problem. This is analogous to checking a malloc() call for NULL.

If you are in fact failing, add an include statement for errno.h to the top, and then check the value of variable "errno". This will be the error code that tells you why the allocation failed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.