在c程序中运行shell命令

问题描述:

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

+1

顺便说一句,如果你想运行一个shell命令或其他可执行文件,这并不重要。不管你使用'system()'还是'fork()/ exec()'方法,只需要一个可执行文件。也许你想相应地编辑你的问题的标题? – Jens 2011-04-12 21:29:26

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

+0

可能与exec()或其变体一起使用。 – PhD 2011-04-10 01:12:17

+1

'system'会让子进程等待shell命令 - 'exec'会用shell替换子进程。 – rlc 2011-04-10 01:13:09

+0

@Ronald:没有。它用另一个进程替换子进程。从OP中不清楚他是要运行另一个程序还是一个shell命令行,但如果是后者,那么只有system()会做到这一点。 exec不涉及shell。 – 2011-04-10 01:15:33

当然,只是forkexec:使用fork创建一个新的进程,在子进程中,使用exec开始与您的命令外壳。 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); 
    } 
} 
+0

exec不涉及shell。假设OP想要运行ls | grep -v你好'。这将与系统一起工作,但不适用于exec。 – 2011-04-10 01:17:48

+0

OP可以将这些传递给shell - 系统做同样的事情(但在后台执行另一个'fork'&'exec')。 – rlc 2011-04-10 01:22:21

尝试这样的代码:

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

这让我觉得太快和肮脏,因为这会从命令退出直到主退出时创建一个僵尸进程。一个行为良好的Unix程序会希望避免这种情况。查看使用'waitpid'的其他答案。 – Jens 2011-04-13 11:38:17

+0

对不起。我对* nix APIs并不是很满意:)。 – JackMc 2011-04-14 02:02:06

什么简单的功放与system ("command &")的命令?