关于创建共享内存并提供父/子进程之间的通信

时间:2012-10-23 23:38:11

标签: c process ipc shared-memory

嗨,我正在尝试实现在子进程和父进程之间使用共享内存的示例。目标是子进程必须计算具有给定大小的斐波那契系列作为用户的输入并将每个数字写为数组的元素。在该过程之后将打印出该数组。问题是如果我创建这个内存段并在fork()操作之前附加它它工作正常,在我做fork()操作之后,子进程可以到达该内存段并正确生成数组,最后父进程可以打印输出孩子完成工作后的数组。代码是这样的;

create memory segment
attach memory segment
initialize the array elements to zero
fork()
if(pid==0)// Child Process
call the child function and send the pointer of a structure which includes the array and array size
return to parent and printout the array properly

这是我实施的第一个例子。但是,我正在尝试使用另一种方式,因为您可以看到下面的完整代码;

#include <stdlib.h>
#include <stdio.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>

#define MAX_SEQUENCE 10

typedef struct {

long fib_sequence[MAX_SEQUENCE];
int sequence_size;

} shared_data;

void child_func(shared_data* dataPtr);

void main(int argc,char *argv[]){

    int shmID,size,status,i;
    shared_data* dataPtr;
    pid_t pid;

            if((pid=fork())<0){
                printf("Error while fork()\n");
                exit(0);
            }

            else if(pid>0){ // Parent Process

                if((shmID = shmget(IPC_PRIVATE, MAX_SEQUENCE*sizeof(long), IPC_CREAT | 0666))<0){
                    printf("Allocation process was unsuccesfull\n");
                    exit(0);
                }

                dataPtr = (shared_data*) shmat(shmID,NULL,0);

                for(i=0; i<MAX_SEQUENCE; i++)
                    dataPtr->fib_sequence[i]==0;

                dataPtr->sequence_size = atoi(argv[1]);

                if((dataPtr->sequence_size) < 0){
                    printf("You entered an invalid(negative) size number\n");
                    exit(0);
                }

                else if((dataPtr->sequence_size) > MAX_SEQUENCE){
                    printf("Please enter a value less than MAX_VALUE\n");
                    exit(0);
                }

                wait(status); // Wait untill child finishes its job

                for(i=0; i<dataPtr->sequence_size; i++)
                    printf("%ld ", dataPtr->fib_sequence[i]);

                printf("\n");
                shmdt((void *) dataPtr);
                shmctl(shmID,IPC_RMID,NULL);
            }

            else{ // Child Process
                child_func(dataPtr);
                exit(0);
                }
} 

void child_func(shared_data* dataPtr){

    int index;

    printf("I am in Child Process\n");
    printf("Size of array %d\n", dataPtr->sequence_size);

    dataPtr->fib_sequence[0];

    if((dataPtr->sequence_size) > 0){

        dataPtr->fib_sequence[1]=1;

        for(index=2; index < dataPtr->sequence_size; index++)
            dataPtr->fib_sequence[index] = dataPtr->fib_sequence[index-1] + dataPtr->fib_sequence[index-2];

    }

}

当我在第二个例子进入子进程时运行它会打印出无意义的dataPtr->fib_sequence值。我很好奇几个问题;

  • 在第二个示例中,为什么它会在子项中打印错误的dataPtr-> size;
  • 在第一个示例中,我们可以承认我们在父进程中创建并附加内存段,因为我们在fork()操作之前执行此操作

0 个答案:

没有答案