-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-1.c
68 lines (57 loc) · 1.57 KB
/
02-1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<stdio.h>
#include<unistd.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<sys/types.h>
#define PERMS (S_IRUSR|S_IWUSR)
#define MAX 10
typedef struct
{
long fib[MAX];
int size;
}Sharedata;
int main(int argc,char* argv[]){
int i,size;
pid_t pid;
int segment_id;
Sharedata* share_memory;
if(argc != 2){
fprintf(stderr, "Usage: ./shm-fib<sequence size>\n");
return -1;
}
size = atoi(argv[1]);
if(size > MAX){
fprintf(stderr, " size must be < %d\n", MAX );
return -1;
}
if( (segment_id = shmget(IPC_PRIVATE, sizeof(Sharedata), PERMS)) == -1 ) { //(见注1)
fprintf(stderr, "Unable to create shared memory segment\n");
return 1;
}
printf("create share memory segment%d\n",segment_id);
if( (share_memory = (Sharedata *) shmat(segment_id,0,0))== (Sharedata*)-1 ){
fprintf(stderr, "Unable to attach to segment %d\n",segment_id );
return 0;
}
share_memory->size = size;
if((pid = fork()) == (pid_t)-1){
return 1;
}
if(pid == 0) {
printf("CHILD: shared memory attached at address %p\n", share_memory );
share_memory->fib[0] = 0;
share_memory->fib[1] = 1;
for(i = 2;i < share_memory->size;i++){
share_memory->fib[i] = share_memory->fib[i-1]+ share_memory->fib[i-2];
//printf("CHILD:%d:%ld\n",i,share_memory->fib[i] );
}
shmdt((void *)share_memory);
}else{//父进程
wait(NULL);
for(i=0;i<share_memory->size;i++){
printf("Parent:%d:%ld\n",i,share_memory->fib[i] );
}
shmdt((void*) share_memory);
shmctl(segment_id,IPC_PRIVATE,NULL);
}
}