Skip to content

Instantly share code, notes, and snippets.

@hamadu
Last active August 7, 2017 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamadu/cbe913850b2143e71b7e5ccd780d8171 to your computer and use it in GitHub Desktop.
Save hamadu/cbe913850b2143e71b7e5ccd780d8171 to your computer and use it in GitHub Desktop.
open then fork / fork then open(for each process)
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_error_and_exit() {
printf("error(%d): %s\n", errno, strerror(errno));
exit(1);
}
int main(int argc, char* argv[]) {
pid_t result = fork();
if (result == -1) {
print_error_and_exit();
}
int fd = open("./src.txt", O_RDONLY);
if (fd == -1) {
print_error_and_exit();
}
if (result == 0) {
char buf[6];
read(fd, buf, 6);
printf("hi. this is child process : %s\n", buf);
} else {
sleep(3);
char buf[6];
read(fd, buf, 6);
printf("hi. this is parent process : %s\n", buf);
}
return 0;
}
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_error_and_exit() {
printf("error(%d): %s\n", errno, strerror(errno));
exit(1);
}
int main(int argc, char* argv[]) {
int fd = open("./src.txt", O_RDONLY);
if (fd == -1) {
print_error_and_exit();
}
pid_t result = fork();
if (result == -1) {
print_error_and_exit();
}
if (result == 0) {
char buf[6];
read(fd, buf, 6);
printf("hi. this is child process : %s\n", buf);
} else {
sleep(3);
char buf[6];
read(fd, buf, 6);
printf("hi. this is parent process : %s\n", buf);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment