Hello everyone,
i was trying to sincronize 2 non child procceses with a binary semaphore and it is working but, for some reason it is not blocking the CS.
when i execute the emisor script, it creates the semaphore and, a thread its created and i block with wait, and post the fragment of code i want, i checked with getvalue, and in the receptor script, i tried with O_CREAT | O_EXCL to verify if the semaphore its busy, and yeah, but i dont know why its not blocking, any ideas guys?
this are my codes:
Code:
/*
ping.c
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
#define SNAME "/sem"
int value;
sem_t *semaphore;
//pthread_t thread;
int size(char *string){
int counter = 1, string_size = 0;
while (counter) {
if (string[string_size] != NULL)
string_size++;
else
counter = 0;
}
return string_size;
}
void *play(void *index){ //recibe el indice del hilo
char *text = "PING";
printf("valor del semaforo fuera de la S.C: %d\n", value);
sem_wait(&semaphore);
printf("valor del semaforo dentroe la S.C: %d\n", value);
for (size_t i = 0; i < size(text); i++){
printf("%c\n", text[i]);
sleep(2);
}
sem_post(&semaphore);
}
int main(int argc, char *argv[]) {
semaphore = sem_open(SNAME, O_CREAT, 0666, 1);
sem_getvalue(semaphore, &value);
if (semaphore == -1) {
perror("ERROR EN SEMAFORO");
exit(-1);
}
//while(1){
pthread_t thread;
pthread_create(&thread, NULL, play, NULL);
pthread_join(thread, NULL);
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//}
sem_close(semaphore);
sem_unlink(SNAME);
return 0;
}
Code:
/*
pong.c
*/
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define KEY 666
#define TAM_BUFFER 256
/*Cada posicion de la cola de mensajes sera una estructura
Puede contener lo que sea (cualquier tipo de variables)*/
typedef struct{
long i;
char msg[TAM_BUFFER];
}mensaje;
int main(int argc, char *argv[]) {
int id_cola_mensajes, e_cola_mensajes, long_msg; //id, error, tamano
id_cola_mensajes = msgget(KEY, 0660 | IPC_CREAT); //Crea la cola de mensaje y retorna el identificador de la misma
if (id_cola_mensajes == -1) {
perror("Error ID_COLA_MENSAJES");
exit(-1);
}
int counter = 0;
while(counter < 5){
mensaje saludo;
e_cola_mensajes = msgrcv(id_cola_mensajes, &saludo, TAM_BUFFER, 0, 0);
if (e_cola_mensajes == -1) {
perror("Error msgrcv");
exit(-1);
}
printf("El mensaje es: %s\n", saludo.msg);
counter++;
}
msgctl(id_cola_mensajes, IPC_RMID, NULL);
return 0;
}
I would appreciate any help
thanks in advice,
bless