1

I am trying to understand how fork in c work. The problem that I am trying to solve is; given f(upper), I am trying to find f(1) + f(2) + .. f(upper). I wanted to do multi process programming to have fork each child process and have each child process calculate f(x).

So f(1) , f(2) ... f(upper) is calculated by each child process.

The parent process should calculate following f(1) + .. + f(upper). Here is my code

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include<sys/shm.h>
#include<sys/ipc.h>

int upper = 0;
int n = 0;

int main(int argc, char*argv[]){
    pid_t pid;
    if(argc != 2){
      printf("Input one argument");
      return -1;
    }
    upper =  atoi(argv[1]);


    int segment_id;
    int *s;
    pid_t *pids;
    pids = (pid_t *) malloc(sizeof(int) * upper);
    s = (int *) malloc(sizeof(int) * upper);


    key_t key = 4141;
    if((segment_id = shmget(key, upper * sizeof(int), IPC_CREAT | 0667))< 0) perror("shmget: failure");

    if((s = shmat(segment_id, NULL, 0)) == (char *) -1){
      perror("shmat : failure");
      exit(1);
    }
    for(int i = 1; i <= upper; i++){
      pid = fork();
      if(pid == 0) {
        n = i;
        break;
      }
      pids[i] = pid;
    }

    if(pid > 0){
      wait(1 * upper);
      int totalSum;
      for(int i = 0; i < upper; i++){
        totalSum += s[i];
      }
  printf("Total sum = %d", totalSum);


} else {
  sleep(2);
  int sum = 0;
  for(int i = 0; i <= n; i++){
    sum += i;
  }
  s[n - 1] = sum;
  printf("n => %d : sum %d\n", n, sum);

}
}

However whenever I try to run this program with argument more than 6. I get Invalid argument error.

1
  • What's the idea behind this wait(1 * upper);, please? Commented Sep 17, 2016 at 15:24

1 Answer 1

2

You are writing outside of the bounds of pids

pids = (pid_t *) malloc(sizeof(int) * upper);
...
for(int i = 1; i <= upper; i++){
  pid = fork();
  if(pid == 0) {
    n = i;
    break;
  }
  pids[i] = pid; /* Here */
}

Change to

for(int i = 1; i < upper; i++){
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.