Linux 在 ac 程序中运行 shell 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5609074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:36:15  来源:igfitidea点击:

Running a shell command in a c program

clinuxshell

提问by wonnie

I want to run a shell command in my c program. But the thing is that i don't want to make my program wait until the command performed. No need to read the shell command's output (it returns no data anyway) So basically, is that possible?

我想在我的 c 程序中运行一个 shell 命令。但问题是我不想让我的程序等到命令执行。无需读取 shell 命令的输出(无论如何它不返回任何数据) 所以基本上,这可能吗?

采纳答案by Stefano Borini

fork()and system()is what you need

fork()并且system()是你所需要的

回答by rlc

Sure, just forkand exec: use forkto create a new process and, in the child process, use execto start the shell with your command. execvtakes the arguments you would normally give to the shell.

当然,只是forkexec: 用于fork创建一个新进程,并且在子进程中,用于使用exec您的命令启动外壳程序。execv接受您通常会提供给 shell 的参数。

Your code could look like this:

您的代码可能如下所示:

pid_t child_pid = fork();
if (child_pid == 0)
{   // in child
    /* set up arguments */
    // launch here
    execv("/bin/sh", args);
    // if you ever get here, there's been an error - handle it
}
else if (child_pid < 0)
{   // handle error
}

the child process will send a SIGCHLDsignal when it dies. This code quoted from the POSIX standard (SUSv4) will handle that:

子进程SIGCHLD在它死亡时会发送一个信号。从 POSIX 标准 (SUSv4) 引用的这段代码将处理:

static void
handle_sigchld(int signum, siginfo_t *sinfo, void *unused)
{
    int status;

    /*
     * Obtain status information for the child which
     * caused the SIGCHLD signal and write its exit code
     * to stdout.
    */
    if (sinfo->si_code != CLD_EXITED)
    {
        static char msg[] = "wrong si_code\n";
        write(2, msg, sizeof msg - 1);
    }
    else if (waitpid(sinfo->si_pid, &status, 0) == -1)
    {
        static char msg[] = "waitpid() failed\n";
        write(2, msg, sizeof msg - 1);
    }
    else if (!WIFEXITED(status))
    {
        static char msg[] = "WIFEXITED was false\n";
        write(2, msg, sizeof msg - 1);
    }
    else
    {
        int code = WEXITSTATUS(status);
        char buf[2];
        buf[0] = '0' + code;
        buf[1] = '\n';
        write(1, buf, 2);
    }
}

回答by HymanMc

Try code like this:

试试这样的代码:

#include <stdlib.h>
#include <unistd.h>
int main(int argc, char ** argv)
{
     if (!fork())
     {
         execv("ls", {"myDir"}); /* Your command with arguments instead of ls. */
     }
}

回答by Jens

What about simply amping the command with system ("command &")?

简单地用 放大命令system ("command &")怎么样?