简体   繁体   中英

Initialize an int in a struct for shared memory

I have an int that keeps track of words in a queue, but I am working with shared memory that should persist across multiple executions. Therefore, I can't simply state

int words = 0;

as a global variable because it will be overwritten each time I run the program. My struct currently looks like this

typedef struct {
  /* List of words stored in the FIFO. */
  Word list[ MAX_WORDS ];
  int words;

} FIFO;

I only need to initialize 'words' to 0 for the first run, and after that the value should persist through shared memory, but I'm not sure how to do this without it being reset to 0 each run.

Any help would be awesome, thanks!

When you create a new shared memory area, it's initialised to zeros automatically. That's the case for both shmget on Linux and CreateFileMapping on Windows. Likely the same on other systems, but you'll have to search in the docs. In practice that means as long as you have proper locking scheme implemented, your app will see only 2 states of the shared memory - either all zeros (you're the first one to open it), or already initialised (another instance opened the shared memory before).

I'm not sure you really want shared memory though. If by "should persist across multiple executions" you mean executions of multiple processes at the same time, then this answer applies. But if you want to run your app, then shut it down, then run it again and have the same FIFO available, then you need to just write it into some file, or an embedded/external database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM