Facebook
From Gracious Macaw, 3 Years ago, written in C#.
This paste is a reply to Re: Re: Re: Re: ss from Smelly Gibbon - go back
Embed
Viewing differences between Re: Re: Re: Re: ss and Re: Re: Re: Re: Re: ss
#include 
#include 
#include 
#include 
#include 
int main( void )
{
union semun //...tę strukturę musimy zdefiniować we własnym zakresie
semun
{
int count; value; struct semid_ds *stats;
*stat;
unsigned short int *array;struct *array; struct seminfo *infos;
*info;
 
control;
//...struktury wykorzystywane przez semop()
control;
 key_t key;
 int flag,semid;
 
struct sembuf P0={ 0,-1,0 },V0={ 0,1,0 },Z0={ 0,0,0 };
struct sembuf P1={ 1,-1,0 },V1={ 1,1,0 },Z1={ 1,0,0 };
//...i cała reszta
key_t key; pid_t pid;
int semid,flag,nsems,step;
key=ftok( "/tmp", 'k'+'m' );flag=IPC_CREAT 
sems;
 key = ftok( "/tmp",'k'+'m' ); flag = IPC_CREAT 
| S_IRUSR | S_IWUSR; nsems = 2;
S_IWUSR;
 
semid = semget( key,nsems,flag );
key,1,flag);
 
control.count value =+1; semctl( semid,0x0,SETVAL,control );
sems.sem_num 
1; semctl(semid,0,SETVAL,control);
control.count 
0; sems.sem_flg 5; semctl(semid,1,SETVAL,control); //czyli będzie 5 cykli
pid = fork(); //...uaktywniamy proces potomny
for( step=0;step0x0;
switch( (int)fork() 
)
{
if( !pid ) //...to wyłacznie dla potomka
{
printf( "[%u]...procesu potomny...start\n",(unsigned)getpid() );
case -1: perror( "...fork()...\t" ); exit( 1 ); break;
case 0:
sems.sem_op =-1; 
semop( semid,&P0,1 ); //...ustawiamy semafor '0'
printf( "[%u]...krytyczna...start\n",(unsigned)getpid() );
sleep( 1 
semid,&sems,1 );
printf( "[%u]...krytyczna...stop\n",(unsigned)getpid() "...child...\t:%u\n",(unsigned)getpid() );
sems.sem_op =+2; semop( semid,&V0,1 ); //...i zwalniamy semafor '0'
//...jeszcze zwiększymy o 1 wartość semafora 1,
// blokującego proces nadrzędny
semid,&sems,1 );
break;
default:
sems.sem_op =-2; 
semop( semid,&P1,1 ); //...zwiększamy wartość o '1' dla
semid,&sems,1 );
printf( "[%u]...procesu potomny...stop\n\n",(unsigned)getpid() "...master...\t:%u\n",(unsigned)getpid() );
sems.sem_op =+1; semop( semid,&sems,1 );
break;
}
} //...no i załóżmy, że to wszystko, co miał zrobić potomek/potomkowie
/* Jeżeli pozostawimy ten fragment w komentarzu, to...
if( !pid )
{
printf( "[%u]...proces potomny zwalnia pamięć\n",(unsigned)getpid());
exit( 0 );
}
...potomek wykona i całą resztę kodu (kiedy zakończy pętlę)*/
semop( semid,&Z1,1); //...na tym semaforze zatrzymał się parent
//...przechodzi go w momencie kiedy, właściwą wartość ustawi potomek
printf( "[%u]...proces nadrzędny odzyskał sterowanie\n", (unsigned) getpid());
//...na koniec usuwany semafor z pomięci
semctl( semid,0x0,IPC_RMID );
return 0;
}

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

Title Name Language When
Re: Re: Re: Re: Re: Re: ss Commodious Cat csharp 3 Years ago.