AAE-CNAS-Labs/Topic-3-Forking/task_2_4.c

82 lines
2.6 KiB
C

//
// Written for Computer Networks and Systems lab classes
// AUTHOR : Sergiusz Warga
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
const char * get_timestamp() {
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");
pid = fork();
if (pid == -1) { // If something went wrong.
perror("Fork: ");
exit(EXIT_FAILURE);
}
if (pid != 0) { // If this is a parent process.
printf("===\n%s\nI am a parent.\nMy PID is: %d\n===", get_timestamp(), getpid());
sleep(1);
kill(getpid(), SIGTERM);
} else {
printf("===\n%s\nI am a child.\nMy PID is: %d\nMy PPID is: %d\n===", get_timestamp(), getpid(), getppid());
sleep(1);
printf("===\n%s\nI am a child.\nMy PID is: %d\nMy PPID is: %d\n===", get_timestamp(), getpid(), getppid());
sleep(1);
printf("===\n%s\nI am a child.\nMy PID is: %d\nMy PPID is: %d\n===", get_timestamp(), getpid(), getppid());
// When parent is killed PPID of its child process becomes 1 (and so the init process becomes a new parent).
}
}
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("===\n%s\nI am a child.\nMy PID is: %d\nMy PPID is: %d\n===", get_timestamp(), getpid(), getppid());
sleep(1);
kill(getpid(), SIGTERM);
} else {
printf("===\n%s\nI am a parent.\nMy PID is: %d\n===", get_timestamp(), getpid());
sleep(1);
printf("===\n%s\nI am a parent.\nMy PID is: %d\n===", get_timestamp(), getpid());
sleep(1);
printf("===\n%s\nI am a parent.\nMy PID is: %d\n===", get_timestamp(), getpid());
}
}
int main() {
int status;
pid_t pid;
printf("%s: Grandparent process has PID: %d\n", get_timestamp(), getpid());
pid = fork();
if (pid == 0) { // If child process
printf("%s: Process with PID %d will execute funs.\n", get_timestamp(), getpid());
child_before_parent();
sleep(5);
parent_before_child();
sleep(5);
} else { // If parent process
printf("%s: Grandparent's child process has PID: %d\n", get_timestamp(), pid);
sleep(12);
}
return 0;
}