簡體   English   中英

如何在c ++中使用system()命令獲取進程的pid

[英]How to get pid of process executed with system() command in c++

當我們使用system()命令時,程序會等待它完成,但我正在使用system()並使用負載平衡服務器執行一個process ,因為該程序在執行系統命令后立即進入下一行。 請注意,該process可能不完整。

system("./my_script");

// after this I want to see whether it is complete or not using its pid.
// But how do i Know PID?
IsScriptExecutionComplete();

簡單回答:你做不到。

system()的目的是阻止何時執行命令。

但你可以像這樣“欺騙”:

pid_t system2(const char * command, int * infp, int * outfp)
{
    int p_stdin[2];
    int p_stdout[2];
    pid_t pid;

    if (pipe(p_stdin) == -1)
        return -1;

    if (pipe(p_stdout) == -1) {
        close(p_stdin[0]);
        close(p_stdin[1]);
        return -1;
    }

    pid = fork();

    if (pid < 0) {
        close(p_stdin[0]);
        close(p_stdin[1]);
        close(p_stdout[0]);
        close(p_stdout[1]);
        return pid;
    } else if (pid == 0) {
        close(p_stdin[1]);
        dup2(p_stdin[0], 0);
        close(p_stdout[0]);
        dup2(p_stdout[1], 1);
        dup2(::open("/dev/null", O_RDONLY), 2);
        /// Close all other descriptors for the safety sake.
        for (int i = 3; i < 4096; ++i)
            ::close(i);

        setsid();
        execl("/bin/sh", "sh", "-c", command, NULL);
        _exit(1);
    }

    close(p_stdin[0]);
    close(p_stdout[1]);

    if (infp == NULL) {
        close(p_stdin[1]);
    } else {
        *infp = p_stdin[1];
    }

    if (outfp == NULL) {
        close(p_stdout[0]);
    } else {
        *outfp = p_stdout[0];
    }

    return pid;
}

在這里,您不僅可以擁有流程的PID ,還可以擁有STDINSTDOUT 玩得開心!

我自己不是這方面的專家,但如果你看一下系統手冊頁

system()通過調用/ bin / sh -c命令執行命令中指定的命令,並在命令完成后返回

您可以在正在執行的命令/腳本中進入后台(並立即返回),但我認為系統中沒有針對該情況的特定規定。

我能想到的想法是:

  1. 您的命令可能會通過返回代碼返回pid。
  2. 您的代碼可能希望在活動進程中查找命令的名稱(例如,類似於unix的環境中的/ proc API)。
  3. 您可能希望使用fork / exec自己啟動命令(而不是通過SHELL)

您可以通過以下代碼檢查命令的退出狀態:

int ret = system("./my_script");

if (WIFEXITED(ret) && !WEXITSTATUS(ret))
{
    printf("Completed successfully\n"); ///successful 
}
else
{
    printf("execution failed\n"); //error
}

正如其他答案所說,無論如何, std::system阻塞直到完成。 但是,如果您想異步運行子進程並且您可以使用 boost,則可以使用boost.process ( ref ):

#include <boost/process.hpp>

namespace bp = boost::process;

bp::child c(bp::search_path("echo"), "hello world");

std::cout << c.id() << std::endl;
// ... do something with ID ...

c.wait();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM