Datei #fbtzkq87-2875 - C - Quellcode
Hochgeladen von tie - 09/03/2010 17:14 - 25 Zugriffe
Quellcode
/*Nguyen Hoanh TienLab 5. ex1p*/#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sched.h>#include <signal.h>#include <sys/wait.h>#include <time.h>#include <semaphore.h>#include <string.h>#define STACKSIZE 10000#define NUMPROCS 3#define ROUNDS 10int n = 0 ;
sem_t s;int cnt=0;
int _pipe[2];
void _do( int i) {
if (i<0){
perror(NULL);
exit(0);
}}int child () {
int id = cnt++;
printf("%d\n", id);
int i=0 ;
for ( ; i < ROUNDS ; i ++ ) {
// Add your entry protocol hereint value;printf("process %d wants to read\n",id);
_do( read(_pipe[0],&value,sizeof(value)) );
printf("process %d done reading; value=%d\n",id,value);
// Start of critical section -- simulation of slow n++int tmp = n ;
int sleeptime = rand()%20000 ;
if ( sleeptime > 10000 ) usleep(sleeptime) ;
n = tmp + 1 ;
// End of critical section// Add your exit protocol hereprintf("process %d wants to write\n",id);
_do( write(_pipe[1],&id,sizeof(id)) );
printf("process %d done writing\n",id);
}return 0 ;
}int main ( int argc, char ** argv ) {
int i ;void * p ;
srand(time(NULL));
int value=0;
pipe(p);
printf("process dad wants to write\n");
_do( write(_pipe[1],&value,sizeof(value)) );
printf("done\n");
for ( i = 0 ; i < NUMPROCS ; i ++ ) {
p = malloc(STACKSIZE) ;
if ( p == NULL ) {
printf("Error allocating memory\n") ;
exit(1) ;
}// create a child that shares the data segment// the stack must be at the top of the allocated areaint c = clone(child,p+STACKSIZE-1,CLONE_VM|SIGCHLD,NULL) ;
if ( c < 0 ) {
perror(NULL) ;
exit(1) ;
}}_do(write(_pipe[1],&value,sizeof(value)));
for ( ; i > 0 ; i -- ) wait(NULL) ;
printf("n=%d\n",n);
return 0 ;
}
