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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
|
#include <sys/mman.h> // mmap()
#include <unistd.h> // fork()
#include <sys/wait.h> // wait()
#include <semaphore.h> // sem_init(), Link with -pthread
#include <errno.h> // errno
#include <stdint.h> // uint32_t
#include <stdio.h> // printf()
int do_fork1();
int do_fork2();
int parent();
int worker_gl();
int worker_sdl();
typedef struct {
sem_t worker_gl_can_render, worker_sdl_can_render, parent_can_read_result;
int scene;
uint32_t framebuf[256*256];
} shm_t;
shm_t *shm;
int main() {
shm = mmap(NULL, sizeof(shm_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
if (sem_init(&shm->worker_gl_can_render, 1, 0) < 0) return 1;
if (sem_init(&shm->worker_sdl_can_render, 1, 0) < 0) return 2;
if (sem_init(&shm->parent_can_read_result, 1, 0) < 0) return 3;
shm->scene = 0;
return do_fork1();
}
int do_fork1() {
switch (fork()) {
case -1: return 4; break;
case 0: return worker_gl(); break;
default: return do_fork2(); break;
}
}
int do_fork2() {
switch (fork()) {
case -1: return 5; break;
case 0: return worker_sdl(); break;
default: return parent(); break;
}
}
int parent() {
int i, child_status;
shm->scene++;
printf("parent1 %i\n", shm->scene);
for(i=0;i<4;i++) {
if ( sem_post(&shm->worker_sdl_can_render) == -1 ) {
return 6;
}
while ( sem_wait(&shm->parent_can_read_result) == -1 ) {
switch(errno) {
case EINTR:
case EAGAIN:
break;
default:
return 7;
}
}
printf("parent2 %i\n", shm->scene);
if ( sem_post(&shm->worker_gl_can_render) == -1 ) {
return 6;
}
while ( sem_wait(&shm->parent_can_read_result) == -1 ) {
switch(errno) {
case EINTR:
case EAGAIN:
break;
default:
return 8;
}
}
printf("parent3 %i\n", shm->scene);
}
if ( wait(&child_status) != -1 ) {
if ( child_status > 0 ) return child_status;
}
if ( wait(&child_status) != -1 ) {
if ( child_status > 0 ) return child_status;
}
return 0;
}
int worker_gl() {
int done=0;
while ( !done ) {
while ( sem_wait(&shm->worker_gl_can_render) == -1 ) {
switch(errno) {
case EINTR:
case EAGAIN:
break;
default:
return 10;
}
}
printf("worker_gl %i\n", shm->scene);
shm->scene++;
if ( sem_post(&shm->parent_can_read_result) == -1 ) {
return 11;
}
}
return 0;
}
int worker_sdl() {
int done=0;
while ( !done ) {
while ( sem_wait(&shm->worker_sdl_can_render) == -1 ) {
switch(errno) {
case EINTR:
case EAGAIN:
break;
default:
return 20;
}
}
printf("worker_sdl %i\n", shm->scene);
shm->scene++;
if ( sem_post(&shm->parent_can_read_result) == -1 ) {
return 21;
}
}
return 0;
}
|