I have a client server project using semaphores. I run both from the same folder, and they use the same key. Now, I want the server to lock the semaphore, so Client can't run commands until server frees it, but the client ignores the server's lock. I do not understand where my mistake is. Server code:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <signal.h>
#include <sys/shm.h>
#include <sys/stat.h>
#define FLAGS IPC_CREAT | 0644
union semun {
int val;
struct semid_ds *buf;
ushort *array; };
union semun semarg;
struct sembuf sops[1];
int main() {
semarg.val=1;
int resultsCreator=open("results.txt",O_CREAT|O_RDWR);
key_t key;
key = ftok("results.txt", 'k');
int shmid = shmget(key, 12, FLAGS);
int semfor = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666);
semctl ( semfor , 0 , SETVAL , semarg );
sops->sem_num = 0;
sops->sem_flg = 0;
sops->sem_op = -1;
int k = semop ( semfor , sops , 1 ); //lock the semaphore
char* shmaddr;
int numWaiting =0;
while(1){
sleep(2); //CHECK EVERY 2 SECONDS IF SOMEONE IS WAITING
numWaiting = semctl(semfor, 0, GETNCNT, semarg);
if(numWaiting==0){
printf("none waiting\n");
continue; }
printf("more than one waiter\n"); //NEVER GETS HERE
} //END WHILE
Client code:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <signal.h>
#include <sys/shm.h>
#include <sys/stat.h>
#define FLAGS IPC_CREAT | 0644
union semun {
int val;
struct semid_ds *buf;
ushort *array;
};
union semun semarg;
struct sembuf sops[1];
int main()
{
key_t key;
key = ftok("results.txt", 'k');
int shmid = shmget(key, 12, FLAGS);
semarg.val=1;
int semfor = semget(key, 0, 0666);
semctl ( semfor , 0 , SETVAL , semarg );
sops->sem_num = 0;
sops->sem_flg = 0;
sops->sem_op = -1;
semop ( semfor , sops , 1 );
printf("skipped lock\n"); //PRINTS IT, EVEN WHEN IT'S STILL LOCKED
sops->sem_op = 1;
semop ( semfor , sops , 1 );
return 0;
}
why does the client ignore the server's semaphore lock?