I am trying to understand fork, sleep... commmands.
I want to do 4 children and one parent operation exactly in this order. Parent> child1> child4> child2> child3. The tasks of these processes are as I wrote in the code below. In this code I have 1 parent, 3 child and 1 grandson(child4 is a grandson). How can I make transactions in this order? I tried to put a sleep on each if's but the program finished without waiting for input in child2.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(void)
{
int n1 = fork();
int n2 = fork();
int input;
if (n1 > 0 && n2 > 0) {
int n3=fork();
if(n3==0)
{ //3th child
printf("3th child process id is %d (parent: %d) \n", getpid(),getppid());
if(input == getppid()) {
printf("matched!\n"); }
else {
printf("not matched!\n"); }
printf("program ended\n");
}
else {
printf("parent process id is %d (parent: %d)\n", getpid(),getppid());
sleep(1);
}
}
else if (n1 == 0 && n2 > 0)
{
printf("1th child process id is %d (parent: %d)\n",getpid(),getppid());
FILE * fp;
fp = fopen ("xx.txt", "w+");
printf("file was created...\n");
sleep(1);
}
else if (n1 > 0 && n2 == 0)
{
printf("2th child process id is %d (parent: %d) \n", getpid(),getppid());
printf("Enter a key: \n");
scanf("%d",&input);
FILE * fp;
fp = fopen ("xx.txt", "w+");
fprintf(fp, "%d", input);
printf("input has been written to the txt file!\n");
}
else {
//4th child
printf("4th child grandson process id is %d (parent: %d)\n", getpid(),getppid());
printf("say me password!\n");
}
return (0);
}