简体   繁体   中英

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.

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 :-)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM