简体   繁体   English

cpp程序中系统功能的使用

[英]usage of system function in cpp program

Please explain the syntax of: system(const char *command); 请解释以下语法:system(const char * command);

I want to use this function for running the command on unix sytem. 我想使用此功能在Unix系统上运行命令。 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. 请记住,调用系统与调用fork和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. 我曾经遇到过服务器上的TCP / IP套接字死掉的问题,因为客户端正在调用系统,该系统创建了一个与服务器不服务的新套接字连接。

I don't see how the syntax can be a problem: 我看不出语法可能是个问题:

system( "foo" );

executes the program called foo, via your preferred shell. 通过您的首选外壳程序执行名为foo的程序。

为每次调用生成一个命令行,然后一次将这些命令行传递到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++ 这是代码,如何在C ++中实现system()命令

#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. 请记住, const char *command是一个字符串,您可以将任何字符串值作为参数传递,并将其发送到命令行。

i think Anter is interested in a example: 我认为Anter对一个示例感兴趣:

for instance to remove a file in a directory: 例如删除目录中的文件:

system("/bin/rm -rf /home/ederek/file.txt"); 系统(“ / bin / rm -rf /home/ederek/file.txt”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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