Trying to pass variables to child process

433 views Asked by At

I'm trying to pass variables to a function that forks, most seem to work, but I need to give each an id which I'm trying to pass in an argv[5] which isn't declared before. My code keeps seg faulting and I can't figure out why. Any ideas?

main

char* arg_list_consumer[] = {
        "./consume",
        argv[1], 
        argv[2],
        NULL
    };
    char* arg_list_producer[] = {
        "./produce",
        argv[1], 
        argv[2],
        argv[3],
        argv[4],
        argv[5],
        NULL
    };
   if (getppid()==1){
        producerID=0;
   }
   if(producerID==0){
        for(i=1; i<P; i++){
            sprintf(arg_list_producer[5], "%d", i);
            spawn ("./produce", arg_list_producer);
        }
        for(i=0; i<C; i++){
            sprintf(arg_list_consumer[5], "%d", i);
            spawn ("./consume", arg_list_consumer);
        }
    }

spawn

int spawn (char* program, char** arg_list)
{
  pid_t child_pid;
  /* Duplicate this process.  */
  child_pid = fork();

  if (child_pid != 0)
    /* This is the parent process.  */
    return child_pid;
  else {
    /* Now execute PROGRAM, searching for it in the path.  */
    execvp (program, arg_list);
    /* The execvp function returns only if an error occurs.  */
    fprintf (stderr, "an error occurred in execvp\n");
    abort ();
  }
}
1

There are 1 answers

0
master_latch On BEST ANSWER

arg_list_consumer is declared to only have 4 entries. Thus, it is an invalid memory operation to index into it with [5].

If you want to assign a value to arg_list_consumer[5], you must declare the array to be at least of size 6 pointers (or you can throw in a few more NULLs to make it have a size of at least 6 pointers).

Then, if you want to use sprintf to store something, you must already have space allocated in the destination string. Since you just have an array of pointers, this means you must use malloc to allocate some space:

arg_list_consumer[5] = malloc(sizeof(char)*10);
sprintf(arg_list_consume[5], "%d", i);

(I used 10 but you should obviously use whatever length you think necessary).