c++ - 如何在 C++ 中获取使用 system() 命令执行的进程的 pid

标签 c++ process pid

当我们使用 system() 命令时,程序会等到它完成,但我正在使用 system() 执行一个 process 并使用 load平衡服务器由于哪个程序在执行系统命令后立即进入下一行。请注意,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。玩得开心!

关于c++ - 如何在 C++ 中获取使用 system() 命令执行的进程的 pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22802902/

相关文章:

c++ - FANN:使用从多个文件读取的数据训练 ANN 时发生内存泄漏

c - 为什么我在命令行上看不到 execvp() 的结果?

c# - 打开资源管理器窗口并等待它关闭

python - Python中进程执行检查并获取PID

c++ - 调用父类中的方法

c++ - 控制到达非空函数的末尾(仅在特定的 IDE 上)

c++ - LibPrivoxy : unresolved external symbol __declspec(dllimport) int __stdcall StartPrivoxy(char *)

java - 我们如何检测 main() 线程是否已死亡但所有生成的 thread() 线程都在运行?

Python 授予读/写文件的完全权限

php - 无法在 PHP 脚本中运行 Linux "awk"命令