简体   繁体   中英

usage of system function in cpp program

Please explain the syntax of: system(const char *command);

I want to use this function for running the command on unix sytem. I need to execute(automate) several test cases with the same command but,they also have other input values which are different.how do I reuse this code for all the test-cases.

int main()
{
    char *base = "./your_testcase " ;
    char aux[50] = "./your_testcase " ;
    char *args[] = {"arg1" ,"arg2" ,"arg3"};
    int nargs = 3;

    for(i=0;i < nargs;i++)
    {
        /* Add arg to the end of the command */
        strcat(aux,args[i]) ;
        /* Call command with parameter */
        system(aux);
        /* Reset aux to just the system call with no parameters */
        strcpy(aux,base);
    }
}

Keep in mind that calling system is the same as calling fork and execl. That mean you need to be aware of things like open socket descriptors and file descriptors. I once had a problem with a TCP/IP socket dying on a server because a client was calling system which created a new socket connection to the server that was not being serviced.

I don't see how the syntax can be a problem:

system( "foo" );

executes the program called foo, via your preferred shell.

为每次调用生成一个命令行,然后一次将这些命令行传递到system()。

See also the question: 'How to call an external program with parameters?;

How to call an external program with parameters?

我会避免使用system()函数,这是为什么这可能不是一个好主意的链接

Here is the code, how to implement system() command in c++

#include <cstdlib>
 
 int main()
 {
    system("pause");
    return 0;
 }
system(const char *command)

Is used to execute a command on the command line of the current operating system. It is generally not the best idea to use this because the commands are platform specific. Keep in mind that const char *command is a string and you can pass any string value as a parameter and it will be sent to the command line.

i think Anter is interested in a example:

for instance to remove a file in a directory:

system("/bin/rm -rf /home/ederek/file.txt");

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