Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Using system() for Windows commands

I'm new to C++, and I've read and heard that using system calls is bad practice. So what if you need to use system() to run a Windows command like ipconfig or netstat. Is it still evil or is that considered an acceptable use of system()? I'm writing a program to collect a variety of information about the system and I use system() many times and pipe the output into text files for review.

like image 929
Son of a Sailor Avatar asked Aug 05 '13 17:08

Son of a Sailor


People also ask

What does system () do in Windows?

Using system(), we can execute any command that can run on terminal if operating system allows. For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.

What does system () do in C?

System() Function in C/C++ It is used to pass the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed. <stdlib. h> or <cstdlib> should be included to call this function.

What does system in C return?

system() returns the exit code of the process you start.


1 Answers

Most of the calls you'd make have Windows API calls you can use directly. Ideally, you'd just call the appropriate Windows API call instead of launching a process, writing to a file, then parsing the file.

That being said, on Windows, CreateProcess will launch a process and provide you a lot more control than a call to system. This includes using STARTUPINFO to provide your own HANDLE for the process standard output stream, which means you can directly read from the process without writing to a file.

like image 132
Reed Copsey Avatar answered Oct 04 '22 15:10

Reed Copsey