I know there is some question about this already, but I don't understand what I'm doing wrong here.
I'm reading numbers from file, and storing them into array.
Now I want to create process that the parent is reading 10 numbers, then the children read the other numbers, add them together and send to the parent process, but for some reason the return value I'm getting is wrong. what I'm missing here?
I added image to demonstrate
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
int my_read(char *arg1);
int main(int argc, char *argv[])
{
my_read("numbers.txt");
}
int my_read(char *arg1)
{
int status;
int avg = 0;
int p, i;
int arr[26];
FILE *file = fopen(arg1, "r");
if (NULL == file)
{
printf("file can't be opened \n");
}
fscanf(file, "%d", &i);
while (!feof(file))
{
arr[p] = i;
p++;
fscanf(file, "%d", &i);
}
arr[25] = i;
// fork
printf("I am the parent: %d\n", (int)getpid());
pid_t pid = fork();
if (pid < 0)
{ /* error occurred */
perror("Fork failed");
}
if (pid == 0)
{ /* child process */
printf("I am the child with pid %d\n", (int)getpid());
for (i = 10; i < 26; i++)
{
printf("%d\n", arr[i]);
avg += arr[i];
}
exit(avg);//send to parent
}
/* parent process */
for (i = 0; i < 10; i++)
{
printf("%d\n", arr[i]);
}
wait(&status);
printf("I am the parent: %d\n", (int)getpid());
printf("%d\n", status);
fclose(file);
return (0);
}