AAE-CNAS-Labs/Topic-2/task_2_4.c
2021-03-10 17:42:09 +01:00

57 lines
1.3 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>
void parent_before_child() {
pid_t pid;
printf("parent_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);
} 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.
}
}
void child_before_parent() {
pid_t pid;
printf("child_before_parent()\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 child.\n");
kill(getpid(), SIGKILL);
} else {
sleep(1);
printf("I am a parent.\n");
}
}
int main() {
pid_t pid;
pid = fork();
if (pid == 0) {
child_before_parent();
sleep(1);
parent_before_child();
sleep(1);
}
sleep(5);
return 0;
}