Datei #fbtzkq87-2875 - C - Quellcode

Hochgeladen von tie - 09/03/2010 17:14 - 25 Zugriffe
Quellcode
  1. /*
  2.    Nguyen Hoanh Tien
  3.    Lab 5. ex1p
  4. */
  5. #include   <stdio.h>
  6. #include   <stdlib.h>
  7. #include   <unistd.h>
  8. #include   <sched.h>
  9. #include   <signal.h>
  10. #include   <sys/wait.h>
  11. #include   <time.h>
  12. #include   <semaphore.h>
  13. #include <string.h>
  14. #define STACKSIZE 10000
  15. #define NUMPROCS 3
  16. #define ROUNDS 10
  17.  
  18. int n = 0 ;
  19.  
  20. sem_t s;
  21. int cnt=0;
  22. int _pipe[2];
  23.  
  24. void _do( int i) {
  25. 	if (i<0){
  26. 		perror(NULL);
  27. 		exit(0);
  28. 	}
  29. }
  30.  
  31.  
  32. int child () {
  33. 	int id = cnt++;
  34. 	printf("%d\n", id);
  35.  
  36. 	int i=0 ;
  37. 	for ( ; i < ROUNDS ; i ++ ) {
  38. 		// Add your entry protocol here
  39. 		int value;
  40. 		printf("process %d wants to read\n",id);
  41. 		_do( read(_pipe[0],&value,sizeof(value)) );
  42. 		printf("process %d done reading; value=%d\n",id,value);
  43.  
  44. 		// Start of critical section -- simulation of slow n++
  45. 		int tmp = n ;
  46. 		int sleeptime = rand()%20000 ;
  47. 		if ( sleeptime > 10000 ) usleep(sleeptime) ;
  48. 		n = tmp + 1 ;
  49. 		// End of critical section
  50.  
  51. 		// Add your exit protocol here
  52. 		printf("process %d wants to write\n",id);
  53. 		_do( write(_pipe[1],&id,sizeof(id)) );
  54. 		printf("process %d done writing\n",id);
  55. 	}
  56. 	return 0 ;
  57. }
  58.  
  59. int main ( int argc, char ** argv ) {
  60. 	int i ;
  61. 	void * p ;
  62. 	srand(time(NULL));
  63.  
  64. 	int value=0;
  65.  
  66. 	pipe(p);
  67. 	printf("process dad wants to write\n");
  68. 	_do( write(_pipe[1],&value,sizeof(value)) );
  69. 	printf("done\n");
  70.  
  71. 	for ( i = 0 ; i < NUMPROCS ; i ++ ) {
  72. 		p = malloc(STACKSIZE) ;
  73. 		if ( p == NULL ) {
  74. 			printf("Error allocating memory\n") ;
  75. 			exit(1) ;
  76. 		}
  77. 		// create a child that shares the data segment
  78. 		// the stack must be at the top of the allocated area
  79. 		int c = clone(child,p+STACKSIZE-1,CLONE_VM|SIGCHLD,NULL) ;
  80. 		if ( c < 0 ) {
  81. 			perror(NULL) ;
  82. 			exit(1) ;
  83. 		}
  84. 	}
  85. 	_do(write(_pipe[1],&value,sizeof(value)));
  86. 	for ( ; i > 0 ; i -- ) wait(NULL) ;
  87. 	printf("n=%d\n",n);
  88. 	return 0 ;
  89. }