Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shmget is not working

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <sys/shm.h>
int main() {
        int i=0;
        int shmid;
        int *mem=(int*)malloc(10*sizeof(int));
        key_t key;
        key=1234;
        pid_t pid;

        shmid=shmget(1234,sizeof(*mem), IPC_CREAT|0666);
        if(shmid==-1) {
             printf("shmget error\n");
             return -1;
        }
        mem=shmat(shmid, NULL, 0);

        if(mem==(int*)-1) {
              printf("shmat error\n");
              return -1;
        }

        for(;i<10;i++) {
               *(mem+i)=0;
        }

        pid=fork();

        if(pid<0) {
               fprintf(stderr,"Fork Failed");
               printf("array : ");
        }
        else if (pid==0) {
               printf("producer is created.\n");
               printf("array : ");

               for(i=0;i<10;i++) {
                         printf("%d ", *(mem+i));
               }
               printf("\n");
               for(i=0;i<10;i++) {
                      *(mem+i)=i+1;
               }
         }
         else {
                wait(NULL);
                printf("consumer takes control of array.\n");
                printf("array : ");
               for(i=0;i<10;i++) {
                      printf("%d ", *(mem+i));
               }
               printf("\n");
               printf("consumer is done.\n");
               printf("array : ");
               for(i=0;i<10;i++) {
                            *(mem+i)=-1;
                            printf("%d ", *(mem+i));
               }
               printf("\ndone.");
        }
        free(mem);
       return 0;
}               

Parent process and child process share an array. So I decide to share memory between these processes. However, shmget function is fail, that means if i run the program, print value is shmget error. I don't know what the problem is. I tried to static allocation of array, dynamic allocation of array, etc. What's the problem? I use Cygwin.

like image 394
Semin Han Avatar asked Apr 30 '16 18:04

Semin Han


1 Answers

From Cygwin's Implementation Notes:

The XSI IPC functions semctl, semget, semop, shmat, shmctl, shmdt, shmget, msgctl, msgget, msgrcv and msgsnd are only available when cygserver is running.

More on the Cygserver here: https://cygwin.com/cygwin-ug-net/using-cygserver.html

like image 57
alk Avatar answered Oct 18 '22 08:10

alk