I am trying fork for the very first time. I have a file with list of integers and I want every line to fork off a child, the child processes the line and writes something in the output file. Basically the for loop starts with number of lines in the input file and goes in a loop, every line should fork a child and after the child is done the fork should launch another child. I am having trouble doing this because before the first child finishes its work the second child starts and in between the parent is also doing some execution.
Edit: the code looks something like this:
void dosomething(flag)
{
}
void forkingfunction(int size, int array[],char *outputfile)
{
int i,j,starting=1,temp=1,status;
for(i=0;i<size;i++,temp++)
{
pid_t pID = fork();
if (pID == 0) // child
{
printf("\nchild pid %d\n",getpid());
const int count = dosomething(flag);
if(flag==1)
{
_exit(EXIT_SUCCESS);
kill(pID,SIGKILL);
}
else
{
FILE *fp;
fp = fopen(outputfile, "a+");
if (fp == NULL)
{perror("Unable to open the output file:");}
for (i = 0; i < len; i++)
{
if (solution[i])
{
fprintf(fp," %u ",array[i]);
}
}
fprintf(fp,"=%d\n",sum);
}
_exit(EXIT_SUCCESS);
kill(pID,SIGKILL);
}
else if (pID < 0) // failed to fork
{
perror("Failed to fork:");
}
else
{
// wait(NULL);
if ((pID = wait(&status)) == -1)
{
perror("Error in wait:");
}
}
}
}
void readingfile(char *inputfile,char *outputfile)
{
FILE *myFile = fopen(input, "r");
if (myFile == NULL)
{
perror("Error: Failed to open file.");
}
//code to get number of lines
while ((c=getc(myFile)) != EOF)
{
//puts values of file in an array for processing
}
forkingfunction(size,array,output);
// close file
fclose(myFile);
}
int main(int argc, char **argv)
{
readingfile(inputfilename,outputfilename);
return 0;
}