2016-04-30 5 views
1
#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; 
}    

Übergeordneter Prozess und untergeordneter Prozess teilen sich ein Array. Also beschließe ich, das Gedächtnis zwischen diesen Prozessen zu teilen. Die shmget-Funktion ist jedoch fehlgeschlagen, dh wenn ich das Programm ausführe, ist der Wert shmget error. Ich weiß nicht, was das Problem ist. Ich habe versucht, eine statische Zuweisung von Array, dynamische Zuweisung von Array, etc. Was ist das Problem? Ich benutze Cygwin.shmget funktioniert nicht

+1

Sie * Sie * wissen, dass 'sizeof (* mem)' die Größe ** gibt man ** 'int'? –

+0

Ich fühlte diesen Punkt ist seltsam, so änderte ich meinen Code shmget (key, 100, IPC_CREAT | 0666); stattdessen. aber es hat immer noch die Fehlermeldung –

+0

Dieser Aufruf 'mem = shmat (shmid, NULL, 0);' leckt den Speicher hier zuordnen: 'int * mem = (int *) malloc (10 * sizeof (int));'. – alk

Antwort

Verwandte Themen