Note that there are some explanatory texts on larger screens.

plurals
  1. POSharing Multiple Variables Via sys/shm.h
    primarykey
    data
    text
    <p>I am trying to share two different using one shared memory block using the shm.h library. I wrote the following example, where one shared memory block is created and is big enough to hold two integers. I then attach two integers to it and create two processes. The first process increments the first integer. The second process then prints out the value of two integers. But what happens is that both of the integers get incremented.</p> <p>What am I doing wrong? I just started learning how to use shm library.</p> <p>This is the code:</p> <pre><code>#include &lt;sys/sem.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/shm.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int main() { // Declare variables int shmID; int *data1; int *data2; // Create a shared memory segment if((shmID=shmget(IPC_PRIVATE, 2*sizeof(int), 0666 | IPC_CREAT))&lt;0) { fprintf(stderr,"Problem initializing shared memory\n"); perror("main"); return -1; } if((data1=shmat(shmID,NULL,0))==(int *)-1) { fprintf(stderr,"Problem attaching memory 1\n"); perror("main"); return -1; } if((data2=shmat(shmID,NULL,0))==(int *)-1) { fprintf(stderr,"Problem attaching memory 2\n"); perror("main"); return -1; } printf("%p %p\n",data1,data2); (*data1)=0; (*data2)=0; if(fork()) { // Process 1 will be the incrementer for(int i=0;i&lt;100;i++) { (*data1)++; printf("IN: %d\n",(*data1)); sleep(1); } printf("IN DONE\n"); } else { while((*data1)&lt;50) { printf("OUT: %d %d\n",(*data1),(*data2)); sleep(1); } printf("OUT DONE\n"); } } </code></pre> <p>And this is the output:</p> <pre><code>0x7fcd42a97000 0x7fcd42a96000 IN: 1 OUT: 1 1 IN: 2 OUT: 2 2 IN: 3 OUT: 3 3 </code></pre> <p>I am running this on Gentoo Linux.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload