简体   繁体   English

在 C 源代码中使用 linux 命令

[英]Using linux commands in C source code

I want to use Linux commands in C source code.我想在 C 源代码中使用 Linux 命令。

Can I use the System() function?我可以使用System()函数吗? Is this possible on Linux?这在 Linux 上可行吗?

If I can't use System() function, what should I do?如果我不能使用 System() 函数,我该怎么办? I want to "tar xvf example.tar".我想要“tar xvf example.tar”。

You can use system() and exec() functions您可以使用system()exec()函数

If you just want to execute shell command and not looking for any return value then you can use system() function call.如果你只想执行 shell 命令而不寻找任何返回值,那么你可以使用 system() 函数调用。

Using system call is not advisable (see system man page).不建议使用系统调用(请参阅系统手册页)。 I would recommend you using exec() which should be invoked in child process after doing fork().我建议您使用 exec(),它应该在执行 fork() 之后在子进程中调用。

The next alternative can be using popen().下一个替代方法是使用 popen()。

    piff = (FILE *)popen("ls -l", "r");
    if (piff == (FILE *)0)
            return (-1);
    while ((i = read(fileno(piff), buff, sizeof (buf))) == -1) {
    if (errno != EINTR) {
        break;
    }
    (void)pclose(piff);

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

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