#include #include #include #include #include #include #include #include #include char DataFile [] = "data.xxx"; char info [] = "abcdefghijklmnopqrstuvwxyz"; #define OFFSET 5 #define SIZE 12 #define PAUSE 2 int trial = 1; int fd, pid; char buffer[120], myname[20]; void writeAccess(), readAccess(); void fcleanup(int nsig){ unlink(DataFile); printf("cleanup:%s\n", myname); if(nsig) exit(0); } int main(){ int i; fd = creat(DataFile, 0644); write(fd, info, strlen(info)); close(fd); signal(SIGINT, fcleanup); sprintf(myname, fork() ? "B-%06d" : "A-%06d", pid = getpid()); srand(time(NULL)+pid); printf("%s:started\n", myname); fd = open(DataFile, O_RDWR|O_EXCL); printf("%s:opened %s\n", myname, DataFile); for(i=0; i < 30; i++){ if(rand()%2) readAccess(); else writeAccess(); } close(fd); printf("%s:finished\n", myname); wait(NULL); fcleanup(0); return 0; } void writeAccess(){ printf("Write:%s #%d\n", myname, trial); //if(fcntl(fd, F_SETLKW, &lock) <0) if(lockf(fd, F_LOCK, 0) <0) perror("SETLOCK"); printf("\twrite:%s locked\n", myname); sprintf(buffer, "%s #%02d", myname, trial); printf ("\twrite:%s \"%s\"\n", myname, buffer); lseek (fd, (off_t) OFFSET, SEEK_SET); write (fd, buffer, SIZE); sleep (PAUSE); if(lockf(fd, F_ULOCK, 0) <0) perror("F_SETLOCK"); printf("\twrite:%s unlocked\n", myname); trial++; } void readAccess(){ printf("Read:%s #%d\n", myname, trial); if(lockf(fd, F_LOCK, 0) <0) perror("F_SETLKW"); printf("\tread:%s locked\n", myname); lseek(fd, (off_t) OFFSET, SEEK_SET); read (fd, buffer, SIZE); printf("\tcontents:%s \"%*.*s\"\n", myname, SIZE, SIZE, buffer); sleep (PAUSE); if(lockf(fd, F_ULOCK, 0) <0) perror("F_SETLKW"); printf("\tread:%s unlocked\n", myname); trial++; }