Facebook
From Smelly Gibbon, 3 Years ago, written in C#.
This paste is a reply to Re: Re: Re: ss from Denim Moth - view diff
Embed
Download Paste or View Raw
Hits: 106
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/stat.h>
  5. #include <sys/sem.h>
  6. int main( void )
  7. {
  8. union semun //...tę strukturę musimy zdefiniować we własnym zakresie
  9. {
  10. int count; struct semid_ds *stats;
  11. unsigned short int *array;struct seminfo *infos;
  12. } control;
  13. //...struktury wykorzystywane przez semop()
  14. struct sembuf P0={ 0,-1,0 },V0={ 0,1,0 },Z0={ 0,0,0 };
  15. struct sembuf P1={ 1,-1,0 },V1={ 1,1,0 },Z1={ 1,0,0 };
  16. //...i cała reszta
  17. key_t key; pid_t pid;
  18. int semid,flag,nsems,step;
  19. key=ftok( "/tmp", 'k'+'m' );flag=IPC_CREAT | S_IRUSR | S_IWUSR; nsems = 2;
  20. semid = semget( key,nsems,flag );
  21. control.count = 1; semctl(semid,0,SETVAL,control);
  22. control.count = 5; semctl(semid,1,SETVAL,control); //czyli będzie 5 cykli
  23. pid = fork(); //...uaktywniamy proces potomny
  24. for( step=0;step<control.count;step++ )
  25. {
  26. if( !pid ) //...to wyłacznie dla potomka
  27. {
  28. printf( "[%u]...procesu potomny...start\n",(unsigned)getpid() );
  29. semop( semid,&P0,1 ); //...ustawiamy semafor '0'
  30. printf( "[%u]...krytyczna...start\n",(unsigned)getpid() );
  31. sleep( 1 );
  32. printf( "[%u]...krytyczna...stop\n",(unsigned)getpid() );
  33. semop( semid,&V0,1 ); //...i zwalniamy semafor '0'
  34. //...jeszcze zwiększymy o 1 wartość semafora 1,
  35. // blokującego proces nadrzędny
  36. semop( semid,&P1,1 ); //...zwiększamy wartość o '1' dla
  37. printf( "[%u]...procesu potomny...stop\n\n",(unsigned)getpid() );
  38. }
  39. } //...no i załóżmy, że to wszystko, co miał zrobić potomek/potomkowie
  40. /* Jeżeli pozostawimy ten fragment w komentarzu, to...
  41. if( !pid )
  42. {
  43. printf( "[%u]...proces potomny zwalnia pamięć\n",(unsigned)getpid());
  44. exit( 0 );
  45. }
  46. ...potomek wykona i całą resztę kodu (kiedy zakończy pętlę)*/
  47. semop( semid,&Z1,1); //...na tym semaforze zatrzymał się parent
  48. //...przechodzi go w momencie kiedy, właściwą wartość ustawi potomek
  49. printf( "[%u]...proces nadrzędny odzyskał sterowanie\n", (unsigned) getpid());
  50. //...na koniec usuwany semafor z pomięci
  51. semctl( semid,0x0,IPC_RMID );
  52. return 0;
  53. }

Replies to Re: Re: Re: Re: ss rss

Title Name Language When
Re: Re: Re: Re: Re: ss Gracious Macaw csharp 3 Years ago.