Last active
August 7, 2017 13:19
-
-
Save hamadu/cbe913850b2143e71b7e5ccd780d8171 to your computer and use it in GitHub Desktop.
open then fork / fork then open(for each process)
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 <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; | |
} |
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 <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