GIÁO TRÌNH HỆ ĐIỀU HÀNH UNIX - LINUX - Trang 155

1
5

printf(“ Appending to file\n”);

fd = open(“junk.out”, 0_WRONLY| 0_APPEND);

assert(fd>=0);

printf( “ locking file\n”);

rc = flock(fd, LOCK_EX);

assert(rc == 0);


printf(“sleeping for 10 seconds\n”);

sleep(10);


printf(“writing data\n”);

rc = write(fd, sample2, strlen(sample2));

assert(rc == strlen(sample2));


printf(“unlocking file\n”);

rc = flock(fd, LOCK_UN);

assert(rc == 0);


close(fd);

printf(“Reading file \n”);
fd = open(“junk.out”, 0_RDONLY);
assert (fd >=0);

while (1)

{

rc = read (fd, data, sizeof (data) );

if( rc > 0 )

{

data[rc] =0; /* kết thúc xâu */

printf (“ Data read (rc = %d): <%s>\n”, rc, data);

}
else if (rc == 0)

{

printf (“ End of file read \ n”);

break;

} else
{

perror ( “ read error ” );

break;

}

}
close (fd);

printf (“ Fiddling with inode\n”);
fd = open (“ junk.out”, 0_RDONLY);