Created
March 9, 2020 04:40
-
-
Save ekzhang/0ffb3459c27484105a79883c8a28bbe9 to your computer and use it in GitHub Desktop.
File descriptor copying tests with fork() and dup2()
This file contains hidden or 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 <cstdio> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#include <sys/wait.h> | |
using namespace std; | |
int main() { | |
int fd = open("fd.txt", O_CREAT | O_WRONLY | O_TRUNC, 644); | |
char buf[14] = "Hello_world!\n"; | |
write(fd, buf, 13); | |
close(fd); | |
fd = open("fd.txt", O_RDONLY); | |
char rbuf[20] = {0}; | |
int pid = fork(); | |
if (pid) { | |
// parent | |
lseek(fd, 1, SEEK_SET); | |
read(fd, rbuf, 4); | |
printf("Read from parent: %s\n", rbuf); | |
waitpid(pid, 0, 0); | |
} | |
else { | |
// child | |
sleep(1); | |
read(fd, rbuf, 4); | |
printf("Read from child: %s\n", rbuf); | |
} | |
return 0; | |
} |
This file contains hidden or 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 <cstdio> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#include <sys/wait.h> | |
using namespace std; | |
int main() { | |
int fd = open("fd.txt", O_CREAT | O_WRONLY | O_TRUNC, 644); | |
char buf[14] = "Hello_world!\n"; | |
write(fd, buf, 13); | |
close(fd); | |
fd = open("fd.txt", O_RDONLY); | |
char rbuf[20] = {0}; | |
dup2(fd, 42); | |
// original | |
lseek(fd, 1, SEEK_SET); | |
read(fd, rbuf, 4); | |
printf("Read from fd: %s\n", rbuf); | |
// dup2 | |
sleep(1); | |
read(42, rbuf, 4); | |
printf("Read from dup2: %s\n", rbuf); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment