Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice05 / ex5.c
diff options
context:
space:
mode:
Commit3c791c6c357115d4abf71c318c9e7cd7571ea658 (patch)
Author
 Syndamia <kamen@syndamia.com>
2023-12-02 21:25:46 +0200
Committer
 Syndamia <kamen@syndamia.com>
2023-12-02 21:25:46 +0200
Files10705fa10c017e7c1c66d1c8feaca92758acefd0 /Year 3/System programming/Practice05/ex5.c
uni-projects-3c791c6c357115d4abf71c318c9e7cd7571ea658.tar
uni-projects-3c791c6c357115d4abf71c318c9e7cd7571ea658.tar.gz
uni-projects-3c791c6c357115d4abf71c318c9e7cd7571ea658.zip
Parent952bee4ac4e4a97d30fc1d681ff0a9e5168fb9c8 (diff)
[SP/P05] Solved exercises
1 files changed, 39 insertions, 0 deletions
-rw-r--r--Year 3/System programming/Practice05/ex5.c39
diff --git a/Year 3/System programming/Practice05/ex5.c b/Year 3/System programming/Practice05/ex5.c
new file mode 100644
index 0000000..8e7bf15
--- /dev/null
+++ b/Year 3/System programming/Practice05/ex5.c
@@ -0,0 +1,39 @@
+#include <unistd.h> // fork, write, read, close, sleep
+#include <fcntl.h> // open
+#include <stdio.h> // perror
+#include <sys/wait.h> // waitpid, WNOHANG
+
+int main(int argc, char* argv[]) {
+ int f1 = open(argv[1], O_RDONLY);
+ if (f1 < 0) {
+ perror("open");
+ return 1;
+ }
+
+ int f2 = open(argv[2], O_WRONLY | O_CREAT | O_APPEND);
+ if (f2 < 0) {
+ perror("open");
+ return 2;
+ }
+
+ pid_t fpid = fork();
+ if (fpid == 0) { // in child
+ char buf;
+ while (read(f1, &buf, 1)) {
+ write(f2, &buf, 1);
+ sleep(1);
+ }
+ }
+ else {
+ int status = -2;
+ char buf = 'p';
+ while(status == -2) {
+ sleep(2);
+ write(f2, &buf, 1);
+ waitpid(fpid, &status, WNOHANG);
+ }
+ }
+
+ close(f1);
+ close(f2);
+}