Skip to content
Advertisement

Attempting to pass Linux command output into a variable

I have the following code:

JavaScript

With the following output:

JavaScript

As you can see, gpio pin 123 is set to ‘in’ and 124 is set to ‘out’.

However, both gp123 and gp124 are being assigned ‘in’. I am rusty with functions and C. Could you fellas help me out a little please?

More specifically, why is it failing to assign the returned value for each command I read? Is this a local/global variable issue?

Thanks!

EDIT:

JavaScript

This seems to work correctly, is there anything here I should change to be more correct?

Advertisement

Answer

You can’t return a pointer to automatic memory from a function. The path array only exists for the duration of the readCmd function (which should return char*, not an int).

To solve it, you can:

  • declare the array static (or use a global array–pretty much the same thing) and embrace non-reenterability
  • use the heap (malloc the array or use the GNU getline function)
  • ask the caller to provide provide a pointer to where to save the output (its size should be passed in too)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement