#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#define NO_STR "NO!"
#define YES_STR "YES"
#define BYE_STR "BYE"
#define TEMP_FILENAME "descriptor-demo.tmp"
int
main(void)
{
int fd, dup_fd;
pid_t pid;
char buffer[5];
/* Create and write to temporary file */
fd = open(TEMP_FILENAME, O_CREAT | O_RDWR | O_TRUNC | O_EXCL, 0644);
if (fd == -1) {
perror("open");
exit(1);
}
dup_fd = dup(fd);
write(fd, NO_STR, 4);
write(dup_fd, YES_STR, 4);
close(dup_fd);
write(fd, BYE_STR, 4);
/* Move back to zero offset */
lseek(fd, 0, SEEK_SET);
pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
/* Child process */
usleep(250000); /* Sleep for 0.25 seconds to let parent seek */
printf("Child - Reading from the file\n");
read(fd, buffer, 4);
printf("Child - Did child see parent's seek: '%s'\n", buffer);
} else {
/* Parent process */
printf("Parent - Seeking to offset 4\n");
lseek(fd, 4, SEEK_SET);
usleep(500000); /* Sleep for 0.5 seconds to let child read */
read(fd, buffer, 4);
printf("Parent - Read: '%s'\n", buffer);
if (strcmp(buffer, "BYE") == 0) {
printf("Parent - Thus, child's read changed offset!\n");
} else {
printf("Parent - Thus, offset did not change.\n");
}
waitpid(pid, NULL, 0); /* Wait for child to finish */
}
close(fd);
unlink(TEMP_FILENAME); /* Remove temporary file */
return 0;
}