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

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 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题