Reputation: 35
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.
Upvotes: 1
Views: 409
Reputation: 85256
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
.
Upvotes: 1