My code runs backward in time

This commit is contained in:
Sergiusz Warga 2021-03-10 19:46:05 +01:00
parent a2a6040d54
commit b4a3c3aeae

View File

@ -7,51 +7,62 @@
#include <unistd.h> #include <unistd.h>
#include <stdlib.h> #include <stdlib.h>
#include <signal.h> #include <signal.h>
#include <time.h>
void parent_before_child() { void parent_before_child() {
pid_t pid; pid_t pid;
printf("parent_before_child()\n"); printf("\nparent_before_child()\n");
pid = fork(); pid = fork();
if (pid == -1) { // If something went wrong. if (pid == -1) { // If something went wrong.
perror("Fork: "); perror("Fork: ");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (pid != 0) { // If this is a parent process. if (pid != 0) { // If this is a parent process.
printf("I am a parent.\n"); printf("===\nI am a parent.\nMy PID is: %d\n===", getpid());
kill(getpid(), SIGKILL); kill(getpid(), SIGTERM);
} else { } else {
sleep(1); sleep(1);
printf("I am a child\n"); // This line will not be printed, as (usually) parent process will finish 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. // its execution in less than 1 second
} }
} }
void child_before_parent() { void child_before_parent() {
pid_t pid; pid_t pid;
printf("child_before_parent()\n"); printf("\nchild_before_parent()\n");
printf("PID before fork: %d\n", getpid());
pid = fork(); pid = fork();
if (pid == -1) { // If something went wrong. if (pid == -1) { // If something went wrong.
perror("Fork: "); perror("Fork: ");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (pid == 0) { // If this is a parent process. if (pid == 0) { // If this is a parent process.
printf("I am a child.\n"); printf("===\nI am a child.\nMy PID is: %d\n===", getpid());
kill(getpid(), SIGKILL); kill(getpid(), SIGTERM);
} else { } else {
sleep(1); 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() { int main() {
clock_t begin = clock();
pid_t pid; pid_t pid;
printf("%f: Grandparent process has PID: %d\n", time_from_exec(begin), getpid());
pid = fork(); 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(); child_before_parent();
sleep(1); sleep(1);
parent_before_child(); parent_before_child();
sleep(1); 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; return 0;
} }