Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I learn how to make a C++ program interact with the Operating System (Linux)

I am a C++ beginner.

I'd like to create small programs that interact with the operating system (using Kubuntu Linux). So far, I have not been able to locate any tutorial or handbook to get C++ to interface with the OS.

In PHP, I can use the command exec() or the backtick operator to launch commands typically executed in a console. How can I do similar things in C++? How can I get my C++ program to execute any other command? How can I get the output of such commands?

Thanks.

like image 226
augustin Avatar asked Jul 25 '10 12:07

augustin


3 Answers

You can use system() to execute arbitrary commands but, if you want to easily control the input and output with the program, you should look into popen().

For even more control, you can look into doing exactly what a shell might do, creating some extra file descriptors, forking to start another process, setting up file descriptors 0, 1 and 2 (input, output and error) in that process to connect them to your original process file descriptors then exec'ing the program you want to control. This isn't for the faint of heart :-)

like image 183
paxdiablo Avatar answered Oct 02 '22 16:10

paxdiablo


You can use the system() command in stdlib to execute system commands:

#include <stdlib.h>
int main() {
    system("ls -l");
}

system() returns an int as its return value, but the value of the int is system-dependent. If you try and use a command that doesn't exist, you'll get the standard "no such command" output back, and usually a non-zero return value. (For example, running system("ls -l"); on my Windows XP machine here returns a value of 1.

like image 35
Stephen Avatar answered Oct 02 '22 15:10

Stephen


You can use system() as instructed previously or you can use libraries which provide access to standard POSIX API. unistd.h and The GNU C Library include many functions for OS interaction. The possibilities with these libraries are endless as you can implement the functionalities yourself. A simple example: scan a directory for text files with scandir() and print the contents of the files.

like image 34
vtorhonen Avatar answered Oct 02 '22 17:10

vtorhonen