From b4a3c3aeae1b04116c14426aabaed1aada178767 Mon Sep 17 00:00:00 2001 From: EdwardEisenhauer Date: Wed, 10 Mar 2021 19:46:05 +0100 Subject: [PATCH] My code runs backward in time --- Topic-2/task_2_4.c | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/Topic-2/task_2_4.c b/Topic-2/task_2_4.c index 65d2806..8c89ad3 100644 --- a/Topic-2/task_2_4.c +++ b/Topic-2/task_2_4.c @@ -7,51 +7,62 @@ #include #include #include +#include void parent_before_child() { pid_t pid; - printf("parent_before_child()\n"); + printf("\nparent_before_child()\n"); pid = fork(); if (pid == -1) { // If something went wrong. perror("Fork: "); exit(EXIT_FAILURE); } if (pid != 0) { // If this is a parent process. - printf("I am a parent.\n"); - kill(getpid(), SIGKILL); + printf("===\nI am a parent.\nMy PID is: %d\n===", getpid()); + kill(getpid(), SIGTERM); } else { sleep(1); - printf("I am a child\n"); // This line will not be printed, as (usually) parent process will finish - // its execution in less than 1 second. + printf("===\nI am a child.\nMy PID is: %d\n===", getpid()); // This line will not be printed, as (usually) parent process will finish + // its execution in less than 1 second } } void child_before_parent() { pid_t pid; - printf("child_before_parent()\n"); + printf("\nchild_before_parent()\n"); + printf("PID before fork: %d\n", getpid()); pid = fork(); if (pid == -1) { // If something went wrong. perror("Fork: "); exit(EXIT_FAILURE); } if (pid == 0) { // If this is a parent process. - printf("I am a child.\n"); - kill(getpid(), SIGKILL); + printf("===\nI am a child.\nMy PID is: %d\n===", getpid()); + kill(getpid(), SIGTERM); } else { sleep(1); - printf("I am a parent.\n"); + printf("===\nI am a parent.\nMy PID is: %d\n===", getpid()); } } +double time_from_exec(clock_t begin) { + return (double)(clock() - begin)/CLOCKS_PER_SEC; +} + int main() { + clock_t begin = clock(); pid_t pid; + printf("%f: Grandparent process has PID: %d\n", time_from_exec(begin), getpid()); pid = fork(); - if (pid == 0) { + if (pid == 0) { // If child process + printf("%f: Process with PID %d will execute funs.\n", time_from_exec(begin), getpid()); child_before_parent(); sleep(1); parent_before_child(); sleep(1); + } else { // If parent process + printf("%f: Grandparent's child process has PID: %d\n", time_from_exec(begin), pid); + sleep(5); } - sleep(5); return 0; } \ No newline at end of file