首页 > 试题广场 >

In Exercise 3.6,the child proc

[问答题]
In Exercise 3.6,the child process must output the Fibonacci sequence,since the parent and child have their own copies of the data.Another approach to designing this program is to establish a shared-memory segment between the parent and child processes.This technique allows the child to write the contents of the Fibonacci sequence to the shared-memory segment and has the parent output the sequence when the child completes.Because the memory is shared,any changes the child makes to the shared memory will be reflected in the parent process as well.
This program will be structured using POSIX shared memory as described in Section 3.5.1.The program first requires creating the data structure for the shared-memory segment.This is most easily accomplished using a struct.This data structure will contain two items:(1)a fixed-sized array of size MAX SEQUENCE that wil lhold the Fibonacci values;and (2) the size of the sequence the child process is to generate -sequence size where sequence size ≤ MAX_SEQUENCE.These items can be represented in a struct as follows:
#define MAX_SEQUENCE 10

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

The parent process will progress through the following steps:
a.Accept the parameter passed on the command line and perform error checking to ensure that the parameteris ≤ MAX_SEQUENCE.
b.Create a shared-memory segment of size shared_data.
c.Attach the shared-memory segment to its address space.
d.Set the value of sequence_size to the parameter on the command line.
e.Fork the child process and invoke the wait( )system call to wait for the child to finish.
f.Output the value of the Fibonacci sequence in the shared-memory segment.
g.Detach and remove the shared-memory segment.
Because the child process is a copy of the parent,the shared-memory region will be attached to the child’s address space as well.The child process will then write the Fibonacci sequence to shared memory and finally will detach the segment.
One issue of concern with cooperating processes involves synchronization issues.In this exercise,the parent and child processes must be synchronized so that the parent does not output the Fibonacci sequence until the child finishes generating the sequence.These two processes will be synchronized using the wait( ) system call;the parent process will invoke wait( ),which will cause it to be suspended until the child proces sexits.

这道题你会答吗?花几分钟告诉大家答案吧!