How to get the pid of a process executed using the system () command in C ++

When we use the command system(), the program waits for completion, but I execute processusing system()and using the load balance server due to which program goes to the next line immediately after the system command is executed. Please note that this processmay be incomplete.

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();
+4
source share
3 answers

The simple answer is: you cannot.

The goal system()is to block while executing a command.

But you can "cheat" like this:

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 , STDIN STDOUT. !

+7

, :

system() , /bin/sh -c,

/ script, ( ), , .

, , :

  • pid .
  • (,/proc API unix- ).
  • , ( SHELL), fork/exec
+1

You can check the exit status of your team by specifying the following code:

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

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

Source: https://habr.com/ru/post/1534594/


All Articles