user1134316
user1134316

Reputation:

Free memory that sent to background child process as argument

I have an exercise - to implement simple shell. Since I have to implement the background operator ('&'), I can't send the arguments when they are on the buffer (because the new process maybe continue running after the next command and the buffer is overwritten). I allocate memory for each arg list, and because of the process is background and I don't wait for him, I don't know when to free the memory.

How I should do it?

Demonstrating (without buffer):

int main(){
  char **toSend = malloc(sizeof(char*) * 3 );
  toSend[0] = malloc(sizeof(char) * 3);
  strcpy(toSend[0], "ls");
  toSend[1] = malloc(sizeof(char) * 3);
  strcpy(toSend[1], "-a");
  toSend[2] = NULL;
  if( !fork() ){
    int devNull = open("/dev/null", O_WRONLY);
    dup2(devNull, STDOUT_FILENO);
    close(devNull);
    execvp(toSend[0], toSend);
  }
  free(toSend[0]); //???
  free(toSend[1]); //???
  free(toSend);    //???
  return EXIT_SUCCESS;
}  

By the way, I will be happy to know if the using of the devNull pointer for create background process is correct.

Thanks in advance! and sorry for my bad English...

Upvotes: 0

Views: 105

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

What you did is correct.

In the child process, after execvp(), its memory image is replaced by a new program, so you do not need to call free() in it. But you still need to call free() in the parent process, as you did in your example code.

Actually, because parent and child are different processes, you could define toSend as local buffer, instead of allocate memory for it dynamically.

Upvotes: 1

tech_boy
tech_boy

Reputation: 33

free(toSend) will just free the address with it.First you free(toSend[0]) which frees all the address allocated using the first address till it encounters address which was not allocated by toSend pointer.

Upvotes: 0

Related Questions