[2] | 1 | /* Copyright (C) 2009 by Mattia Monga <mattia.monga@unimi.it> */
|
---|
| 2 | /* $Id$ */
|
---|
| 3 |
|
---|
| 4 | #include <unistd.h>
|
---|
| 5 | #include <stdio.h>
|
---|
| 6 | #include <stdlib.h>
|
---|
| 7 | #include <signal.h>
|
---|
| 8 | #include <sched.h>
|
---|
| 9 |
|
---|
| 10 |
|
---|
| 11 | void enter_section(int *s); /* in enter.asm */
|
---|
[15] | 12 | void leave_section(int *s){ *s = 0; }
|
---|
[2] | 13 |
|
---|
[15] | 14 | int run(const int p, void* s){
|
---|
| 15 | int* shared = (int*)s; // alias per comodit\`a
|
---|
| 16 | while (enter_section(&shared[1]), shared[0] < 10) {
|
---|
| 17 | sleep(1);
|
---|
[2] | 18 | printf("Processo figlio (%d). s = %d\n",
|
---|
| 19 | getpid(), shared[0]);
|
---|
| 20 | if (!(shared[0] < 10)){
|
---|
| 21 | printf("Corsa critica!!!!\n");
|
---|
| 22 | abort();
|
---|
| 23 | }
|
---|
| 24 | shared[0] += 1;
|
---|
| 25 | leave_section(&shared[1]);
|
---|
| 26 | sched_yield();
|
---|
| 27 | }
|
---|
[15] | 28 | leave_section(&shared[1]); // il test nel while \`e dopo enter\_section
|
---|
[2] | 29 | return 0;
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | int run0(void*s){ return run(0, s); }
|
---|
| 33 | int run1(void*s){ return run(1, s); }
|
---|
| 34 |
|
---|
| 35 |
|
---|
| 36 | int main(void){
|
---|
| 37 |
|
---|
| 38 | int shared[4] = {0 , 0, 0, 0};
|
---|
| 39 |
|
---|
| 40 | /* int clone(int (*fn)(void *),
|
---|
| 41 | * void *child_stack,
|
---|
| 42 | * int flags,
|
---|
| 43 | * void *arg);
|
---|
| 44 | * crea una copia del chiamante (con le caratteristiche
|
---|
| 45 | * specificate da flags) e lo esegue partendo da fn */
|
---|
| 46 | if (clone(run0, /* il nuovo
|
---|
| 47 | * processo esegue run(shared), vedi quarto
|
---|
| 48 | * parametro */
|
---|
| 49 | malloc(4096)+4096, /* lo stack del nuovo processo
|
---|
| 50 | * (cresce verso il basso!) */
|
---|
[15] | 51 | CLONE_VM | SIGCHLD, /* la (virtual) memory \`e condivisa */
|
---|
[2] | 52 | shared) < 0){
|
---|
| 53 | perror("Errore nella creazione");
|
---|
| 54 | exit(1);
|
---|
| 55 | }
|
---|
| 56 |
|
---|
| 57 | if (clone(run1, malloc(4096)+4096, CLONE_VM | SIGCHLD, shared) < 0){
|
---|
| 58 | perror("Errore nella creazione");
|
---|
| 59 | exit(1);
|
---|
| 60 | }
|
---|
| 61 |
|
---|
| 62 | /* Memoria condivisa: i due figli nell'insieme eseguono 10 o
|
---|
[15] | 63 | * 11 volte: \`e possibile una corsa critica. Il padre
|
---|
[2] | 64 | * condivide shared[0] con i figli */
|
---|
| 65 |
|
---|
| 66 | while(shared[0] < 10) {
|
---|
| 67 | sleep(1);
|
---|
| 68 | printf("Processo padre. s = %d %d %d %d\n",
|
---|
| 69 | shared[0],
|
---|
| 70 | shared[1],
|
---|
| 71 | shared[2],
|
---|
| 72 | shared[3]);
|
---|
| 73 | }
|
---|
| 74 | return 0;
|
---|
| 75 | }
|
---|
| 76 |
|
---|
| 77 |
|
---|
| 78 |
|
---|
| 79 |
|
---|
| 80 |
|
---|
| 81 |
|
---|
| 82 |
|
---|
| 83 | /* Local Variables: */
|
---|
| 84 | /* compile-command: "make -k " */
|
---|
| 85 | /* End: */
|
---|