Search code examples
c++windowsoperating-systemsystem

Is there an alternative to the 'system()' command in C++.?


I have read a lot of answers saying that the system() command is bad. First off, why is it so bad? Second off, is there an alternative that doesn't produce such a security hole? I mostly want to know if there is a way to clear screen in C++. In python I have a clear function that checks the os name and runs either system('cls') or system('clear'). Is this a security hole as well? If so, is there a python alternative?


Solution

  • system functions (across many language, including Python and C++) are not inherently "bad" but they present difficulties for correct use.

    Security

    You need to be absolutely sure that whatever you're executing via system is secure.

    If you write system("echo hello " + name) then you need to be absolutely sure that name cannot be controlled by a malicious user. name = "; rm -rf /" would result in echo hello ; rm -rf /, so if that's coming from a user, via something like a web form or a database, then you need to exercise a lot of caution, and I would recommend a more sophisticated solution than system.

    A call like system("clear") is secure for your purposes.

    Usability

    System calls give you several outputs (I'll give an example for calls to a bash shell):

    • status code (whether the shell indicated an error condition)
    • contents of STDOUT
    • contents of STDERR

    system returns the status code. For commands like ls, you are interested in receiving STDOUT, and you may also check the status code. This is unwieldy with system.

    The Python subprocess module is generally accepted by the community as an easier way to manage these concerns.

    How to manage the console

    If you're trying to manage the console display, you may be interested in a library like ncurses which has broad OS support.

    Adding ncurses as a dependency could be heavy-handed, if clearing the screen is the only thing you need to do. If that's the case, then I see nothing wrong with using system() like you're doing.