嗨,我正在尝试实现在子进程和父进程之间使用共享内存的示例。目标是子进程必须计算具有给定大小的斐波那契系列作为用户的输入并将每个数字写为数组的元素。在该过程之后将打印出该数组。问题是如果我创建这个内存段并在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
值。我很好奇几个问题;
fork()
操作之前执行此操作