What I’m wondering is how running programs communicate with each other, and if someone could post some sample code for how to do this, so I can try it out myself, just for educational purposes.
For example, I’ve worked with databases before, and in my code I always have to “establish a connection to the database.” The database service has to be running before I start my program, or else it will fail. What exactly is going on with that connection and how does it work?
Any sort of communication with the outside world is ultimately mediated by the operating system. There’s various mechanisms available for Inter-process communication, but pipes and network sockets are probably some of the most common. If you’ve ever piped the output of one program into another on a command line shell, those processes were communicating with a pipe. The connection to the database you mentioned is using a network socket, perhaps with a custom protocol. For communicating separate machines in a fairly universal way, you’d probably go with a web service, which generally means passing information through HTTP and possibly XML.
3
There high-level communication possibilities:
- Remote Procedure Calls (Web Services, CORBA etc. included)
- File Transfer
- Shared Database
- Messaging (AMQP, ZeroMQ etc.)
There are also low-level communication possibilities:
- Sockets
- Pipes
- Shared-memory
- Signal
This is not such an easy question to be answered because it envolves distinct types of work.
For the case of a database, for example, it’s usually a connection to a server through TCP/IP protocol, and the database needs to be running because the server needs to be connected so that it receives the request from your code (think that you can’t access an offline website).
However, for the case of other programs, it depends a lot. If it’s just a module written in the same language, you could just import. If it’s a Unix process, you could call system function passing the command. If you want something to be multi-platform, you could use a Restful or a SOAP web service (that’d require internet connection), and so on.
2
To ensure that the database service is running , You can either check whether the service is running, and start or stop it accordingly.
for Windows you should use Windows API to do that accordingly.
here is the example code
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686315(v=vs.85).aspx
and also a different approach here
http://code.msdn.microsoft.com/windowsdesktop/CppWindowsService-cacf4948
1