Shmget返回的值为-1

时间:2016-12-01 11:58:46

标签: c

当我在下面的代码中运行shmget时,它返回的值为-1,我不知道为什么会这样。其他一切似乎都运行良好。代码只是从命令行中取几个数字,然后为它们创建共享内存。数字范围为0到9。

#include <sys/ipc.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <sys/types.h>


int main(int argc, char *argv[])
{
  int numArgc =(int)argc-1;    //number of vauled arguments passed
  int arrayId[numArgc];    
  pid_t pid;           
  int arrSpace[numArgc];       //array to store atoi of values
  int status;

  int *memory;         //pointer to shared memory
  int memoryId;        //check for smhget
  int childPID; 
  int childId;

  if(argc > 8 || argc < 2)     //check number of cmd line arg
  {
    printf("The number of arguments must be between 1 and 7");
    return(0);
  }
  else
  {
    for(int i=1; i<numArgc+1; i++)  //store args as integers
    {
      arrSpace[i]=atoi((argv[i]));
      printf("%d\n", arrSpace[i]);
    }
  }


  memoryId=shmget(IPC_PRIVATE, try, IPC_CREAT | 07546); //create shared 
  printf("%d \n", memoryId);
  if(memoryId<0)
  {
    printf("There was an error with ID.\n");
    return (0);
  }
  printf("%s%d", "Size of shared Memory of parent is \n ", numArgc);

  memory=(int*)shmat(memoryId, NULL, 0);  // attaches shared memory
  if((long)memory == -1)
  {
    printf("There was an error running shmat  .\n");
    return (0);
  }

  printf("Share memory is now: \n");
  for(int i=0; i<numArgc; i++)
  {
    memory[i]=arrSpace[i];
  }
  printMemory(memory, numArgc);

  printf("Beginning fork process");
  for(childId; childId <= numArgc; childId++)
  {
    pid = fork(); //creates new process
    if(pid < 0)
    {
      printf("There was an error during fork process");
      return (0);
    }
    else if(pid == 0)
    {
      ChildProcess(memory, numArgc, childId);
      exit(0);
    }
  }

  ParentProcess(memory, childPID, numArgc, memoryId, status);
  return (0);
}

1 个答案:

答案 0 :(得分:1)

shmget返回-1,因为try变量未定义且权限07546无效。请为内存段传递适当的权限。

#define MEMORY_SIZE 20 //size of memory segment
memoryId=shmget(IPC_PRIVATE, MEMORY_SIZE , IPC_CREAT | 0666); //create shared 
printf("%d \n", memoryId);