在c程序中运行shell命令
我想在我的c程序中运行shell命令。但事情是,我不想让我的程序等待命令执行。不需要读取shell命令的输出(无论如何它都不返回数据)所以基本上,这是可能的吗?在c程序中运行shell命令
当然,只是fork
和exec
:使用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);
}
}
exec不涉及shell。假设OP想要运行ls | grep -v你好'。这将与系统一起工作,但不适用于exec。 – 2011-04-10 01:17:48
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. */
}
}
什么简单的功放与system ("command &")
的命令?
顺便说一句,如果你想运行一个shell命令或其他可执行文件,这并不重要。不管你使用'system()'还是'fork()/ exec()'方法,只需要一个可执行文件。也许你想相应地编辑你的问题的标题? – Jens 2011-04-12 21:29:26