我不明白为什么在父进程中我的数据没有设置为我的子进程中的设置。我在分叉程序之前创建了shared_data结构变量,因此它应该是共享内存,对吗?
以下是代码:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SEQUENCE 20
typedef struct
{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
void fibonacci(shared_data* sdata);
int main ( int argc, char *argv[])
{
pid_t pid, pid1;
shared_data sdata;
/* check for parameter values to program */
int i;
for(i = 0; i < argc; i++)
{
if(strcmp(argv[i], "-ms") == 0)
{
int j = ++i;
if(argv[j])
{
/* set passed in value to the sequence_size */
int paramValue = atoi(argv[j]);
if(paramValue <= MAX_SEQUENCE)
{
sdata.sequence_size = paramValue;
}
else
{
sdata.sequence_size = MAX_SEQUENCE;
}
}
break;
}
}
printf("sequence size: %i\n", sdata.sequence_size);
/* fork a child process */
pid = fork();
if (pid < 0)
{
/* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0)
{
/* child process */
pid1 = getpid();
printf("current child process id = %d\n",pid);
printf("child's parent process id = %d\n",pid1);
fibonacci(&sdata);
printf("child: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[sdata.sequence_size - 1]);
}
else
{
/* parent process */
pid1 = getpid();
printf("current parent process id = %d\n",pid); /* C */
printf("current parent process parent id = %d\n",pid1); /* D */
wait(NULL);
int i =0;
for(i = 0; i < sdata.sequence_size; i++)
{
printf("parent: [%d] Fibonacci Result: %i\n", getpid(), sdata.fib_sequence[i]);
}
}
}
void fibonacci(shared_data* sdata)
{
int first = 0;
int second = 1;
int next;
int i;
for(i = 0; i < sdata->sequence_size; i++)
{
if(i <= 1)
{
next = i;
}
else
{
next = first + second;
sdata->fib_sequence[i] = next;
first = second;
second = next;
}
printf("child: [%d] %i\n", getpid(), next);
}
}