Хрестоматия по программированию на Си в Unix



Системные вызовы и взаимодействие с UNIX. Хрестоматия по программированию на Си в Unix - стр. 3


#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(){ flock_t lock;

printf("Write:%s #%d\n", myname, trial);

lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = (off_t) OFFSET; lock.l_len = (size_t) SIZE;

if(fcntl(fd, F_SETLKW, &lock) <0) perror("F_SETLKW"); 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);

lock.l_type = F_UNLCK; if(fcntl(fd, F_SETLKW, &lock) <0) perror("F_SETLKW");

printf("\twrite:%s unlocked\n", myname);

trial++; }

void readAccess(){ flock_t lock;

printf("Read:%s #%d\n", myname, trial);

lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = (off_t) OFFSET; lock.l_len = (size_t) SIZE;

if(fcntl(fd, F_SETLKW, &lock) <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);

lock.l_type = F_UNLCK; if(fcntl(fd, F_SETLKW, &lock) <0) perror("F_SETLKW");

printf("\tread:%s unlocked\n", myname);




Содержание  Назад  Вперед