weixin_42698519 2020-03-28 17:28 采纳率: 0%
浏览 368
已结题

shm_open error:No such file or directory

操作系统实验共享内存posix新建shm_open(“Sharedmemory”,O_RDWR,0)报错
shm_open error:No such file or directory
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define MAX_SEQUENCE 10
typedef struct{
int fib_sequence[MAX_SEQUENCE];
int sequence_size;
}share_data;

void Fibonacci(int n, int *Fibo){//获得斐波那契数列
if(n == 0){
Fibo[0] = 0;
return;
}

Fibo[0] = 0;
Fibo[1] = 1;
if(n == 1){
    return;
}
for(int i=2; i< n;i++){
    Fibo[i] = Fibo[i-1] + Fibo[i-2];    
} 

}

int main(){
int num;
int shmid;//共享内存ID
share_data *shMemory;//创建结构体指针
pid_t pid;

printf("Please enter a positive number(no more than 10): ");
while(1){
    scanf("%d", &num);
    if(num < 0)  printf("The number less than 0. Please try agian: ");
    else if(num > 10) printf("The number more than 0. Please try agian: ");
    else break;
}

shm_unlink("shared-memory");
if((shmid = shm_open("shared-memory",O_RDWR,0777)) < 0)
{//创建共享内存
    printf("shm_open error:%s\n", strerror(errno));
    return -1;
}

ftruncate(shmid,sizeof(share_data));//定义共享内存区大小
struct stat buf;
if(fstat(shmid,&buf)==-1)
{
     printf("buf error:%s\n", strerror(errno));
     return -1;
}

shMemory=(share_data*)mmap(NULL,buf.st_size,PROT_WRITE|PROT_READ,MAP_SHARED,shmid,0);//给父进程附上共享内存
if(shMemory==MAP_FAILED)
{
     printf("shMemory error:%s\n", strerror(errno));
     return -1;
}
while((pid = fork()) == -1);//创建子进程

if(pid == 0){//在子进程中生成斐波那契数列
    Fibonacci(shMemory->sequence_size, shMemory->fib_sequence);
    exit(0);
}
else if(pid > 0){//父进程中,执行输出
    wait(0);//等待子进程完成
    for(int i = 0; i < shMemory -> sequence_size; i++){
        printf("%d ", shMemory->fib_sequence[i]);
    }
    printf("\n");
    shm_unlink("shared-memory");
    exit(0);
}
return 0;

}

  • 写回答

1条回答 默认 最新

  • 关注
    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退