简体   繁体   中英

Error getting shared memory for creating more than 6 child process

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.

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++){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM