From 79fc63135bf4073dde51466eafea3a524c0b99f8 Mon Sep 17 00:00:00 2001 From: Sergiusz Warga Date: Wed, 10 Mar 2021 22:08:21 +0100 Subject: [PATCH] Excahnged clock() with gettimeofday() --- .gitignore | 3 +++ Topic-2/task_2_4.c | 28 +++++++++++++++++----------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index 9324439..89d6c6e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ cmake-build-debug CMakeLists.txt .idea *.o + +# Apple +.DS_Store \ No newline at end of file diff --git a/Topic-2/task_2_4.c b/Topic-2/task_2_4.c index 8c89ad3..d4e233f 100644 --- a/Topic-2/task_2_4.c +++ b/Topic-2/task_2_4.c @@ -4,11 +4,20 @@ #include #include +#include #include #include #include #include +const char * time_from_main_exec() { + struct timeval now; + gettimeofday(&now, NULL); + char buff[127]; + sprintf(&buff, "us : %d", now.tv_usec); + return buff; +} + void parent_before_child() { pid_t pid; printf("\nparent_before_child()\n"); @@ -18,11 +27,11 @@ void parent_before_child() { exit(EXIT_FAILURE); } if (pid != 0) { // If this is a parent process. - printf("===\nI am a parent.\nMy PID is: %d\n===", getpid()); + printf("===\n%s\nI am a parent.\nMy PID is: %d\n===", time_from_main_exec(), getpid()); kill(getpid(), SIGTERM); } else { sleep(1); - printf("===\nI am a child.\nMy PID is: %d\n===", getpid()); // This line will not be printed, as (usually) parent process will finish + printf("===\n%s\nI am a child.\nMy PID is: %d\n===", time_from_main_exec(), getpid()); // This line will not be printed, as (usually) parent process will finish // its execution in less than 1 second } } @@ -37,31 +46,28 @@ void child_before_parent() { exit(EXIT_FAILURE); } if (pid == 0) { // If this is a parent process. - printf("===\nI am a child.\nMy PID is: %d\n===", getpid()); + printf("===\n%s\nI am a child.\nMy PID is: %d\n===", time_from_main_exec(), getpid()); kill(getpid(), SIGTERM); } else { sleep(1); - printf("===\nI am a parent.\nMy PID is: %d\n===", getpid()); + printf("===\n%s\nI am a parent.\nMy PID is: %d\n===", time_from_main_exec(), 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()); + printf("%s: Grandparent process has PID: %d\n", time_from_main_exec(), getpid()); pid = fork(); if (pid == 0) { // If child process - printf("%f: Process with PID %d will execute funs.\n", time_from_exec(begin), getpid()); + printf("%s: Process with PID %d will execute funs.\n", time_from_main_exec(), 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); + printf("%s: Grandparent's child process has PID: %d\n", time_from_main_exec(), pid); sleep(5); } return 0;