1

Is it possible to send a reference to a variable as a parameter to an executable in C?

Suppose I have a parent process called main which has multiple arrays defined. Now, if I fork() and exec*() a C program called sort per array. My questions are: can I create a sort program which can access by reference an array (defined in main)? How can I pass the reference to an array from main?

The advantage that I see in this implementation is the simplicity that I get as the parent process passes the reference to the array, and once the sort has exited properly, the array will be sorted. (Given, I must write and use the program sort.)

DaveIdito
  • 1,546
  • 14
  • 31
  • 4
    Separate processes cannot readily share data — you'd have to use shared memory. So the whole basis of your question is not directly feasible. – Jonathan Leffler Mar 24 '18 at 03:30

1 Answers1

3

No you cannot. Once a process is executed with a exec*() function, it has no more access to the old process's variables.

man execlp

The exec() family of functions replaces the current process image with a new process image.

You can pass to the execd program values through the argv array of arguments. If that's not possible because you have complex data structures, then you can use shared memory between your programs. See How to use shared memory with Linux in C

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
Pablo
  • 13,271
  • 4
  • 39
  • 59