繁体   English   中英

在ac程序中运行shell命令

[英]Running a shell command in a c program

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

fork()system()就是你所需要的

当然,只需forkexec :使用fork创建一个新进程,并在子进程中使用exec用你的命令启动shell。 execv获取通常给shell的参数。

您的代码可能如下所示:

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
}

子进程在死亡时将发送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);
    }
}

尝试这样的代码:

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

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

暂无
暂无

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

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