操作系统实验共享内存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;
}
截图: