PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 14, 2022

[FIXED] How to get pid of some process started inside child process with help if exec family in C/C++ in linux?

 September 14, 2022     c++, exec, linux     No comments   

Issue

I want to get the pid of some process(let's call it Somebinary) which is started with the help of exec family inside child process and assume Somebinary never stops once started. I want to print the pid of this process from the parent process.

I can't wait in the parent process as the child process will start Somebinary through exec* and that will never stop. I know I can do:

int start(std::string Somebinary){
    pid_t childpid = fork();
    if(childpid == 0){
        freopen(logfile.c_str(), "a+", stdout);
        dup2(1, 2);

        exec*("/bin/sh", "sh", "-c", Somebinary.c_str(), " &", NULL)
        exit(1);
    }
    // print pid of Somebinary from here
    return 0;
}

but I want to reduce extra overhead if possible.

Basically, I want to do the following thing as we do in bash from C/C++:

Bash

$ Somebinary > logfile 2>&1 &
$ pidof Somebinary

I know I can do stdout and stderr redirects with the help of freopen and dup2 in the child process. But the rest is the doubt.

P.S.: this has to be done in Linux

Thanks a lot for the help.


Solution

Note that exec does not "create a process" or change the PID, fork does.

As @kaylum said, childpid is the PID of the exec'd process already. You can just print it:

int start(std::string Somebinary){
    pid_t childpid = fork();
    if(childpid == 0){
        freopen(logfile.c_str(), "a+", stdout);
        dup2(1, 2);

        exec(Somebinary.c_str(), NULL);
        exit(1);
    }
    if (childpid < 0) { // basic error handling
        perror("fork"); return -1;
    }
    // print pid of Somebinary from here
    printf("childpid = %jd\n", (intmax_t) childpid);
    return 0;
}

Also you might want to bypass /bin/sh and exec the Somebinary directly, otherwise you'll get the PID of /bin/sh.



Answered By - rustyx
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing