该程序假设在子进程和父进程之间创建共享内存,其中子进程将一定长度的斐波那契序列(参数)保存到其中,父进程将其吐出。它还假设附加和分离共享内存。除了我收到此错误之外,一切似乎都可以正常工作:
proj2.cpp:40: error: no match for 'operator*' in 'shared_data *shm' error
有什么帮助吗?下面的代码。
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <iostream>
#define MAX_SEQUENCE 10
struct shared_data{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
using namespace std;
char * shm;
int Fibonacci(int n){
int first = 0, second = 1, temp = 0;
shared_data.fib_sequence[0] = first;
shared_data.fib_sequence[1] = second;
for(int i = 2; i<=n; i++){
temp = first + second;
shared_data.fib_sequence[i] = temp;
first = second;
second = temp;
}
return 0;
}
int main(int argc, char *argv[])
{
pid_t pid;
int seg_id;
const int shd = 4096;
seg_id = shmget(IPC_PRIVATE, shd, S_IRUSR | S_IWUSR);
shared_data *shm = shmat(seg_id, NULL, 0);
int number = atoi(argv[1]);
if(number < 0 || number > 10){
cout << "Invalid number. Please enter a number greater than 0 \n";
return(1);
}
shared_data.sequence_size = number;
pid = fork();
if(pid == 0)
Fibonacci(number);
else{
waitpid(pid,0,0);
for (int i = 0; i <= shared_data.sequence_size; i++)
cout << shared_data.fib_sequence[i];
cout << "\n";
}
return 0;
}