首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Shmget返回的值为-1。

Shmget返回的值为-1。
EN

Stack Overflow用户
提问于 2016-12-01 11:58:45
回答 1查看 1.3K关注 0票数 1

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

代码语言:javascript
复制
#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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-01 12:54:24

shmget返回-1,因为try变量是未定义的,权限07546是invalid.Please,为内存段传递适当的权限。

代码语言:javascript
复制
#define MEMORY_SIZE 20 //size of memory segment
memoryId=shmget(IPC_PRIVATE, MEMORY_SIZE , IPC_CREAT | 0666); //create shared 
printf("%d \n", memoryId);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40910119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档