簡體   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