【问题标题】:fibonacci sequence using shared memory in C在 C 中使用共享内存的斐波那契数列
【发布时间】:2012-11-25 14:10:33
【问题描述】:

我有一个问题要解决,但它给了我错误:

2009-EE-182-Part2.c: In function ‘main’:
2009-EE-182-Part2.c:35:13: error: expected identifier or ‘(’ before ‘->’ token
2009-EE-182-Part2.c:40:22: error: expected identifier or ‘(’ before ‘->’ token
2009-EE-182-Part2.c:41:14: error: expected identifier or ‘(’ before ‘->’ token
2009-EE-182-Part2.c:42:22: error: expected expression before ‘shared_data’
2009-EE-182-Part2.c:44:15: error: expected identifier or ‘(’ before ‘->’ token
2009-EE-182-Part2.c:54:15: error: expected expression before ‘shared_data’
2009-EE-182-Part2.c:55:19: error: expected expression before ‘shared_data’

代码是:

# include <stdio.h>
# include <sys/shm.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <unistd.h>
# define MAX_SEQUENCE 10

typedef struct{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;

char* shared_memory; /* a pointer to the shared memory segment */

int main()
{
int a,b,m,n,i,j;
a=0; b=1;
printf("Enter the number of a Fibonacci Sequence:\n");
scanf("%d", &m);

if (m < 0)
        printf("Please enter a non-negative integer\n");
else if (m> MAX_SEQUENCE)
        printf("Please enter an integer less than 10\n");

int segment_id; /* the identifier for the shared memory segment */

int segment_size = sizeof(shared_data); /* the size (in bytes) of the shared memory segment */
segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR); /** allocate  a shared memory segment */
shared_data *shared_memory = shmat(segment_id, NULL, 0); /** attach the shared memory segment */
printf("\nshared memory segment %d attached at address %p\n", segment_id, shared_memory);

shared_data->sequence_size = m;
pid_t pid;
pid = fork();
    if (pid == 0){
        printf("Child is producing the Fibonacci Sequence...\n");
        shared_data->fib_sequence[0] = a;
    shared_data->fib_sequence[1] = b;
        for (i=2;i<shared_data->sequence_size;i++){
        n=a+b;
        shared_data->fib_sequence[i] = n;
        a=b;
        b=n;
        }
        printf("\nChild ends\n"); 
    }
    else{
        printf("Parent is waiting for child to complete...\n");
        wait(NULL);
        printf("Parent ends\n");
    for(i=0;i<= shared_data->sequence_size;i++)
        printf("%ld ", shared_data->fib_sequence[i]);
    }

/**printf("%s \n", shared_memory);  now print out the string from shared memory */

/** now detach the shared memory segment */ 
if ( shmdt(shared_memory) == -1) {
    fprintf(stderr, "Unable to detach\n");
}

/** now remove the shared memory segment */
shmctl(segment_id, IPC_RMID, NULL); 

return 0;
}

声明是 “设计斐波那契程序的一种方法是在父进程和子进程之间建立一个共享内存段。 这种技术允许孩子将斐波那契数列的内容写入共享- 内存段,并让父级在子级完成时输出序列。 因为内存是共享的,所以孩子所做的任何更改都会反映在父母身上 过程也是如此。该程序将使用 POSIX 共享内存构建,如中所述 http://graphics.im.ntu.edu.tw/~robin/courses/os07/code/03proc/shm-posix.c 该程序首先需要为共享内存段创建数据结构。使用结构最容易做到这一点。该数据结构将包含两项: 1. 一个固定大小的数组,大小为 MAX_SEQUENCE,将保存斐波那契值和 2.子进程要生成的序列的大小,即sequence_size,其中 sequence_size ≤ MAX_SEQUENCE。

这些项目可以在结构中表示如下:

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

父进程将通过以下步骤进行: 一种。接受命令行传递的参数并进行错误检查以确保 该参数≤MAX_SEQUENCE。 湾。创建一个大小为 shared_data 的共享内存段。 C。将共享内存段附加到其地址空间。 d。将 sequence_size 的值设置为命令行上的参数。 e. fork 子进程并调用 wait() 系统调用来等待子进程 结束。 F。在共享内存段中输出斐波那契数列的值。 G。分离并移除共享内存段。

共享内存段将附加到孩子的地址空间以及 父母的地址空间。然后子进程会将斐波那契数列写入

共享内存段。父进程和子进程必须同步,以便 父级不会输出斐波那契数列,直到子级完成生成 顺序。 注意:在控制台上显示足够的消息,让用户知道何时执行某个操作 被执行,例如子进程的创建和终止等"

请高手帮忙。

【问题讨论】:

    标签: c posix fork shared-memory fibonacci


    【解决方案1】:

    第一个问题:

    int a,b,m,n,i,j;
    
    sequence.fib_sequence[0] = a;
    sequence.fib_sequence[1] = b;
    

    你永远不会初始化a 和b,因此你会得到垃圾(和未定义的行为)。初始化

    a = 0;
    b = 1;
    

    更深层次的问题:您设置了一个共享内存段,但从不使用它。你用全局

    shared_data sequence;
    

    在子级中写入,在父级中读取。由于该全局与您设置的共享内存无关,因此子项的操作不会修改父项的sequence。

    您应该使用shared_memory,指向要写入和读取的共享内存的指针。所以不是char*,应该是

    shared_data *shared_memory = shmat(...);
    

    然后使用shared_memory-&gt;sequence[i]等。

    修复shared_data/shared_memory 混淆并添加一些错误检查后,程序可能看起来像

    # include <stdlib.h>
    # include <stdio.h>
    # include <sys/shm.h>
    # include <sys/stat.h>
    # include <sys/types.h>
    # include <unistd.h>
    # include <sys/wait.h>
    # include <errno.h>
    
    // So we could use other sizes without editing the source.
    #ifndef MAX_SEQUENCE
    # define MAX_SEQUENCE 10
    #endif
    
    // Check that MAX_SEQUENCE is large enough!
    #if MAX_SEQUENCE < 2
    #error MAX_SEQUENCE must be at least 2
    #endif
    
    typedef struct{
        long fib_sequence[MAX_SEQUENCE];
        int sequence_size;
    } shared_data;
    
    int main()
    {
        int a, b, m, n, i;
        a = 0; b = 1;
        printf("Enter the number of a Fibonacci Sequence:\n");
        // Always check whether input conversion worked
        if (scanf("%d", &m) != 1) {
            printf("Invalid input, couldn't be converted.\n");
            return EXIT_FAILURE;
        }
    
        if (m <= 0) {
            printf("Please enter a positive integer\n");
            return EXIT_FAILURE;  // exit if input is invalid
        } else if (m > MAX_SEQUENCE) {
            printf("Please enter an integer less than %d\n", MAX_SEQUENCE);
            return EXIT_FAILURE;  // exit if input is invalid
        }
    
        /* the identifier for the shared memory segment */
        int segment_id;
    
        /* the size (in bytes) of the shared memory segment */
        size_t segment_size = sizeof(shared_data);
    
        /* allocate  a shared memory segment */
        segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR);
    
        // Check result of shmget
        if (segment_id == -1) {
            perror("shmget failed");
            return EXIT_FAILURE;
        }
    
        /* attach the shared memory segment */
        shared_data *shared_memory = shmat(segment_id, NULL, 0);
    
        // Check whether attaching succeeded
        if ((void*)shared_memory == (void*)-1) {
            perror("shmat failed");
            goto destroy; // clean up
        }
        printf("\nshared memory segment %d attached at address %p\n", segment_id, (void*)shared_memory);
    
        shared_memory->sequence_size = m;
        pid_t pid;
        pid = fork();
        if (pid == 0){
            printf("Child is producing the Fibonacci Sequence...\n");
            shared_memory->fib_sequence[0] = a;
            shared_memory->fib_sequence[1] = b;
            for (i = 2; i < shared_memory->sequence_size; i++){
                n = a+b;
                shared_memory->fib_sequence[i] = n;
                a = b;
                b = n;
            }
            printf("\nChild ends\n"); 
        }
        else{
            printf("Parent is waiting for child to complete...\n");
            wait(NULL);
            printf("Parent ends\n");
            for(i = 0; i < shared_memory->sequence_size; i++) {
                printf("%ld ", shared_memory->fib_sequence[i]);
            }
            printf("\n");
        }
    
        /* now detach the shared memory segment */ 
        if (shmdt(shared_memory) == -1) {
            fprintf(stderr, "Unable to detach\n");
        }
    
        destroy:
        /* now remove the shared memory segment */
        shmctl(segment_id, IPC_RMID, NULL); 
    
        return 0;
    }
    

    【讨论】:

    • 非常感谢。但即使在使用 shared_data *shared_memory = shmat(...);对于我使用的每个shared_data->,它都会出现“预期标识符或'('之前的'->'标记”的错误。例如这部分代码“shared_data->fib_sequence[i] = n;”
    • 错字了,应该是shared_memory-&gt;sequence[i]等,当然,对不起。
    • 我输入的新代码有错误。你能看出这里有什么问题吗?
    • 正如我所说,我最初打错了。 shared_data 是类型,指针是shared_memory,所以你必须将所有shared_data-&gt; 替换为shared_memory-&gt;。这样做可以使其编译并正常工作。您应该删除全局 char *shared_memory; 声明,但它没有被使用。并且您必须#include &lt;sys/wait.h&gt;,并在打印地址时将shared_memory 转换为void*(只要指针具有相同的大小和表示,无论它们指向哪种类型,它都会正常工作,但这是未定义的行为)。而j 未使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多