I wrote a program that given an integer n
as argument creates n-1
child processes.The pid_t
variables used in fork are stored in an array.For each child every pid[i]=-1
except pid[childs_number]=0
.So when i write if(pid[1]==0)
the code inside the if statement belongs to child one(i checked it by printing getpid()
inside).
Code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>
void handler(){
}
int main(int argc, char **argv)
{
int n=argv[1][0]-'0';
pid_t pid[n];
for(int i=1;i<n;i++)
{
pid[i]=fork();
if(pid[i]==0)
{
for(int j=1;j<n;j++)
{
if(i!=j)
{
pid[j]=-1;
}
}
break;
}
wait(0);
}
if(pid[1]==0)
{
signal(SIGINT,handler);
pause;
printf("why");
}
}
So after using pause i expect process with pid[1]=0
to wait for a SIGINT signal in order to continue running.However, running this code prints the string inside the if statement even though i haven't sent a SIGINT signal. Why is this happening and how could i fix it?