0

I'm writing a library where the C program provides an API to a client C program that includes it. As part of its functionality, the C library file popen's a Python script, running a Flask server, which the C program will write to, through a pipe. My problem is, by what path should I invoke the Python file?

My current solution is to write a makefile that places all the user's compiled binaries in a specific bin directory and I hardcode the path from that bin directory to the python file in the variable passed to popen. This is precarious and would cause the system to break if the user moves the binary around.

Directory structure:

.
├── README.md
├── bin
│   └── a.out
├── Makefile
├── src
│   ├── server
│   │   └── server_main.py
│   ├── mylib.c
│   └── mylib.h
└── tests
    └── test_0.c

The current janky C code (in mylib.c):

pype = popen("python3 ../src/server/server_main.py", "w");

Client program can be anywhere, not just in tests directory.

I'm hoping for a way I can make this a less inflexible solution to the user, and not have a relative path in the C file.

  • 1
    Notice that the directory of an executable is not necessarily the current working directory – Antti Haapala -- Слава Україні Aug 17 '19 at 11:29
  • 1
    You could create a configuration file or provide the path on the command line. – Paul Ogilvie Aug 17 '19 at 11:31
  • So the Python program is a dependent resource and is located in a specific subfolder of the final application. Therefore, a possible solution would be for the C program to pass either the path of that subfolder or the path of the executable C file as a required dependency when initializing your C library. Your C library can then use this information to call the Python program. – Stephan Schlecht Aug 17 '19 at 12:07

1 Answers1

0

Various operating systems provide their own idiosyncratic mechanisms for a C program to discover the location of its own binary executable, though there is no universal mechanism for that. If you are willing to rely on an OS-specific mechanism, possibly chosen at build time, then the C program can rely on the Python program to be located at a specific path relative to the executable itself. Then you can support the whole installation directory being moved around as a unit.

If you don't want to rely on any OS-specific behavior, or if you want to support the Python program being located at an arbitrary place, then the only alternatives are for the C program to search for the Python program at runtime -- which is costly and risks selecting the wrong program -- or to tell the C program where the Python program is. There are many conceivable ways to do the latter, but the conventional ones would be via a configuration file and / or a command-line argument and / or an environment variable.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157