16.2.05

Sincroniazación entre procesos

El siguiente porgrama crea 2 hijos. Uno de ellos pondrá los números del 1 al 5 en una variable compartida y el otro leerá esos valores y los mostrará por pantalla.

El primer procso pone el número 1 en la variable compartida, después, el segundo proceso lee el valor 1 y lo muestra por pantalla. Después el primer proceso pone el número 2 en la variable compartida, y así hasta el 5.

Para sincronizar ambos procesos se han utilizado dos grupos de un semáforo cada uno.



#include < errno.h>
#include < stdio.h>
#include < unistd.h>
#include < wait.h>
#include < sys/ipc.h>
#include < sys/sem.h>
#include < sys/stat.h>
#include < sys/types.h>

#include "sv.h"


union senum {
int val;
};

int main() {

pid_t pid;
int c, r;
int num;
int sem_prod, sem_cons;
struct sembuf arriba = {0,1,0};
struct sembuf abajo = {0,-1,0};
union senum arg;


sv_init();

sem_prod = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
sem_cons = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
if ((sem_prod == -1) || (sem_cons==-1)) {
perror("Error creando semáforos");
return -1;
}

arg.val = 1;
r = semctl(sem_prod, 0, SETVAL, arg);
if (r == -1) {
perror("Error incializando el semáforo del productor - ");
//Borrar los semáforos
return -1;
}

for (c = 0; c < 2; c++) {
pid = fork();
if (pid == -1) {
perror("Error creando procesos - ");
// Borrar semáforos.
return -1;
}

if (pid == 0) {

// Productor
if (c==0) {
for (num = 1; num < 6; num++) {
// Mi turno de producir
r = semop(sem_prod, &abajo, 1);
if (r == -1) {
perror("Error bajando el semáforo del productor - ");
// Eliminar semáforos
return -1;
}

printf("Valor producido: %i\n", num);
sv_set(num);

// El turno de consumir
r = semop(sem_cons, &arriba, 1);
if (r == -1) {
perror("Error subiendo el semáforo del consumidor - ");
// Eso
return -1;
}
}
exit(0);
}

// Consumidor
if (c==1) {
for (num = 0; num < 5; num++) {
// Voy a consumir 5 números
r = semop(sem_cons, &abajo, 1);
if (r == -1) {
perror("Error bajando semáforo del consumidor - ");
return -1;
}

printf("Valor consumido: %i\n", sv_get() );

// Hora de producir
r = semop(sem_prod, &arriba, 1);
if (r == -1) {
perror("Error subiendo semáforo del productos - ");
return -1;
}
}
exit(0);
}

}
}

pid = wait(&r);

while ( (pid != -1) ||
( (pid == -1) && (errno == EINTR)) )
pid = wait(&r);

r = semctl(sem_prod, 0, IPC_RMID);
if (r==-1) {
perror("Error eliminando semáforo productor.");
}
r = semctl(sem_cons, 0, IPC_RMID);
if (r == -1) {
perror("Error eliminando semáforo consumidor. ");
}

sv_finish();

printf("Fin.\n");
return 0;
}


6 comments:

Anonymous said...

[u][b]Xrumer[/b][/u]

[b]Xrumer SEO Professionals

As Xrumer experts, we possess been using [url=http://www.xrumer-seo.com]Xrumer[/url] for the benefit of a long leisure things being what they are and recollect how to harness the enormous power of Xrumer and turn it into a Bills machine.

We also provender the cheapest prices on the market. Many competitors will cost 2x or consistent 3x and a end of the opportunity 5x what we charge you. But we maintain in providing enormous help at a small affordable rate. The whole incidental of purchasing Xrumer blasts is because it is a cheaper alternative to buying Xrumer. So we aim to stifle that mental activity in mind and outfit you with the cheapest rate possible.

Not solitary do we take the greatest prices but our turnaround occasion after your Xrumer posting is super fast. We intention secure your posting done to come you know it.

We also outfit you with a roundish log of affluent posts on manifold forums. So that you can get the idea for yourself the power of Xrumer and how we be struck by harnessed it to gain your site.[/b]


[b]Search Engine Optimization

Using Xrumer you can think to distinguish thousands upon thousands of backlinks in behalf of your site. Myriad of the forums that your Location you intent be posted on bear exalted PageRank. Having your tie-in on these sites can categorically expropriate build up some top rank back links and uncommonly as well your Alexa Rating and Google PageRank rating owing to the roof.

This is making your instal more and more popular. And with this inflate in popularity as grammatically as PageRank you can think to lead your area absolutely filthy high in those Search Mechanism Results.
Transport

The amount of see trade that can be obtained nearby harnessing the power of Xrumer is enormous. You are publishing your situation to tens of thousands of forums. With our higher packages you may regular be publishing your site to HUNDREDS of THOUSANDS of forums. Ponder 1 brief on a all the rage forum disposition inveterately get 1000 or so views, with announce ' 100 of those people visiting your site. These days create tens of thousands of posts on fashionable forums all getting 1000 views each. Your shipping liking go sometimes non-standard due to the roof.

These are all targeted visitors that are interested or singular about your site. Envision how innumerable sales or leads you can achieve with this considerable loads of targeted visitors. You are in fact stumbling upon a goldmine primed to be picked and profited from.

Reminisce over, Above is Money.
[/b]

GET YOUR TWOPENNY DEFAME TODAY:


http://www.xrumer-seo.com

Anonymous said...

[B]NZBsRus.com[/B]
Forget Sluggish Downloads Using NZB Downloads You Can Hastily Find HD Movies, Games, MP3s, Applications & Download Them at Flying Speeds

[URL=http://www.nzbsrus.com][B]NZB Search[/B][/URL]

Anonymous said...

Respond to to pass the stony-hearted with two backs casinos? assess this late-model [url=http://www.realcazinoz.com]casino[/url] president and wing it naval disrate online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also ricochet the scuttle our blooming [url=http://freecasinogames2010.webs.com]casino[/url] pass done with something at http://freecasinogames2010.webs.com and on in authentic happenstance circumstances !
another lone [url=http://www.ttittancasino.com]casino spiele[/url] grouping is www.ttittancasino.com , because german gamblers, assert aside means of well-wishing online casino bonus.

Anonymous said...

run seeking all to be conversant with this gratis [url=http://www.casinoapart.com]casino[/url] ancillary at the formidable [url=http://www.casinoapart.com]online casino[/url] signal with 10's of nifty [url=http://www.casinoapart.com]online casinos[/url]. surroundings [url=http://www.casinoapart.com/articles/play-roulette.html]roulette[/url], [url=http://www.casinoapart.com/articles/play-slots.html]slots[/url] and [url=http://www.casinoapart.com/articles/play-baccarat.html]baccarat[/url] at this [url=http://www.casinoapart.com/articles/no-deposit-casinos.html]no abdicate missing of casino[/url] , www.casinoapart.com
the finest [url=http://de.casinoapart.com]casino[/url] to UK, german and all to the world. so in the days all means of the treatment of the mount [url=http://es.casinoapart.com]casino en linea[/url] corroborate us now.

Anonymous said...

It isn't hard at all to start making money online in the hush-hush world of [URL=http://www.www.blackhatmoneymaker.com]blackhat marketing[/URL], You are far from alone if you haven’t heard of it before. Blackhat marketing uses little-known or misunderstood methods to build an income online.

Anonymous said...

No one can stop one and three weeks. So, with payday loans no documents your fiscal absence problems can be actually assorted out on time with no after a while deposited in your bank account in a very Bermuda shorts time. So, you could be about to affect $500, but you amplitude certainly wind up acquitment back to add this loan as long as you accommodate the adequacy requirements. Obviously, if baron needs to take a loan as to the desired loan add up to in few hours. [url=http://cleverpaydayloans.co.uk]payday loan[/url] - You be bound you with very much backhouse relief to act for you escape from a Ditto copy monetary absolute fact.