68 lines
2.0 KiB
C
68 lines
2.0 KiB
C
//
|
|
// Wrote for Computer Networks and Systems lab classes
|
|
// AUTHOR : Sergiusz Warga
|
|
|
|
#include <stdio.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
#include <stdlib.h>
|
|
#include <signal.h>
|
|
#include <time.h>
|
|
|
|
void parent_before_child() {
|
|
pid_t pid;
|
|
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("===\nI am a parent.\nMy PID is: %d\n===", 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
|
|
// its execution in less than 1 second
|
|
}
|
|
}
|
|
|
|
void child_before_parent() {
|
|
pid_t pid;
|
|
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("===\nI am a child.\nMy PID is: %d\n===", getpid());
|
|
kill(getpid(), SIGTERM);
|
|
} else {
|
|
sleep(1);
|
|
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 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);
|
|
}
|
|
return 0;
|
|
} |