Re: Shared Memory...Some Questions.....
- From: Ulrich Eckhardt <doomster@xxxxxxxx>
- Date: Wed, 21 Mar 2007 07:28:41 +0100
Solomon_Man wrote:
int indexId = 0;
if((indexId = shmget(IPC_PRIVATE,sizeof(int),SHM_R|SHM_W))<0)
{
cout<<"ERROR: indexId ="<<indexId<<endl;
cout<<strerror(errno)<<endl;
exit (1);
}
You have an error in you method of programming here, in particular for C++
you could do better. Suggestion:
int shm_create( size_t size, int flags)
{
int res = shmget( IPC_PRIVATE, size, flags);
if(res!=-1)
return res;
int const e = errno;
cout << "shmget() failed, errno=" << e << '(' << strerror(e) << ")\n";
exit(EXIT_FAILURE);
}
What's the difference?
1. You are doing things between shmget() and reading errno that might
affect errno. Save the value immediately!
2. Use EXIT_FAILURE, it documents clearly what is going on.
3. No need to init a variable to zero and then assign a value to it. In
fact I'd consider the if-clause pretty unreadable. Suggestion:
int indexId = shmget(...);
if(indexId == -1)
{ ... }
What else:
The function returns an int, but that is in fact a resource handle that can
be used to access the shared memory. You need to make sure that this
resource is correctly released after use. For that, use RAII (STW if that
doesn't mean anything to you yet). I would suggest you create a wrapper
that behaves like std::auto_ptr, all with its peculiar copying semantics.
With that in place, you could also use exceptions to signal errors which
makes the final code much, much clearer.
int ptheSharedIndex;
ptheSharedIndex = (int)shmat(indexId,0,0);
//attach to the current process
Now, this is plainly wrong: You are casting a pointer to an integer. Do you
know the difference between a pointer-to-X and an X? Further, the rule is
to never use C style casts in C++. If you don't (yet) understand why, at
least accept this for now and don't stray from this path. FYI, the correct
cast is a static_cast and if you try to cast to the wrong type the
compiler will tell you about it as good as it can - the 'int' would have
been flagged as error.
exit(0); //End Process (Main)
Unnecessary, you could have returned here or simply fallen off the end with
the same effect.
Uli
.
- References:
- Shared Memory...Some Questions.....
- From: Solomon_Man
- Shared Memory...Some Questions.....
- Prev by Date: Re: question on ethernet raw socket and vlan tag
- Next by Date: Re: Shared Memory...Some Questions.....
- Previous by thread: Shared Memory...Some Questions.....
- Next by thread: Re: Shared Memory...Some Questions.....
- Index(es):
Relevant Pages
|