Last active
July 4, 2016 10:32
-
-
Save Alexey-N-Chernyshov/cf4c44423bdef47a6d3570c88e1dcede to your computer and use it in GitHub Desktop.
IPC via lseek
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <errno.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <sys/wait.h> | |
int main() { | |
pid_t parent_pid = getpid(); | |
printf("parent pid is %d\n", parent_pid); | |
int fd = open("file.tmp", O_CREAT | O_RDWR); | |
if (fd < 0) { | |
perror("open failure"); | |
exit(EXIT_FAILURE); | |
} | |
off_t offset = lseek(fd, 42, SEEK_SET); // set offset | |
printf("offset is set %zu in parent\n", offset); | |
pid_t pid = fork(); | |
if (pid < 0) { | |
perror("fork failed"); | |
exit(EXIT_FAILURE); | |
} else if (pid > 0) { //parent process | |
printf("parent is waiting for child with pid %d\n", pid); | |
int stat; | |
wait(&stat); | |
printf("child returned stat %d\n", WEXITSTATUS(stat)); | |
offset = lseek(fd, 0, SEEK_CUR); // get the current offset | |
printf("offset in parent now is %zu\n", offset); | |
close(fd); | |
} else if (pid == 0) { //child process | |
pid_t child_pid = getpid(); | |
printf("child pid is %d\n", child_pid); | |
offset = lseek(fd, 64, SEEK_SET); | |
printf("child set offset to %zu\n", offset); | |
close(fd); | |
printf("child exited\n"); | |
return EXIT_SUCCESS; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment