gpt4 book ai didi

c - Shmget 返回值 -1

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:21 27 4
gpt4 key购买 nike

当我在下面的代码中运行 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);
}

最佳答案

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);

关于c - Shmget 返回值 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40910119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com