Monday, 15 April 2013

c - Using fnctl() to lock and unlock file for read and write (multiple Processes) -



c - Using fnctl() to lock and unlock file for read and write (multiple Processes) -

i trying implement concurrent server (i.e. handling multiple processes forking new kid processes).

each of clients perform read/write requests read file.txt located in server. using fnctl() handle syncronization, ie. can have multiple reads 1 write.

this sample code of have done till now:

{ file *file = fopen("file.txt", "w+"); fd = fileno(file); printf("\nthis file descriptor : %d\n", fd); if(file == null) printf("file cannot opened"); printf("\nlocking!!!!"); //initliazing flock construction memset(&lock, 0, sizeof(lock)); //setting 0 value lock.l_type = f_wrlck; //f_rdlck, f_wrlck, f_unlck lock.l_whence = seek_set; //seek_set, seek_cur, seek_end lock.l_start = 0; //offset l_whence lock.l_len = 0; //length, 0 = eof lock.l_pid = getpid(); //the processes's pid //placing write lock on file fcntl(fd, f_setlkw, &lock); printf("\nlocked-------"); fwrite(buff + 1, 1, strlen(buff) - 1, file); //lock_realease(&l); printf("\nhit come in unlock file !"); getchar(); printf("\nfinished writing can unlock file !"); //releasing lock lock.l_type = f_unlck; //unlocks part of file fcntl(fd, f_setlkw,&lock); printf("\nfile unlocked!"); }

can guide me if in right direction please?

maybe. you'll have add together error handling (so notice when locking failed), waiting (when locking failed) , timeouts (when kid stuck , lock never released).

but in experience, process brittle. create single socket instead. allow children connect socket. utilize master process feed commands children. in scenario, master process replaces single file.

this has couple of advantages:

the master process keeps tab on state of children (what working on) , can write tool see statistics. later, can utilize health monitoring. you don't need locking sockets.

c linux client-server

No comments:

Post a Comment