Lets say i have run a simple background process which is:
sleep 25 &
I execute it on the command line as :
> sleep 25 &
[1] 26390
> ps
PID TTY TIME CMD
26390 pts/52 0:00 sleep
6746 pts/52 0:02 tcsh
26391 pts/52 0:00 ps
>
You can see that sleep is executing in the background with pid 26390
Now I try to do the same thing using c++.there are many different system calls to do it btw.
using system
using fork
using pipe
I tried below code:
if(p=fork()){
//Main process
cout<<p<<endl;
}
else{
execv("sleep 20 &",(char **)NULL);
}
}
output is:
> ./a.out
27391
> ps
PID TTY TIME CMD
6746 pts/52 0:02 tcsh
27392 pts/52 0:00 ps
>
You can see that there is no sleep running in the background. Now i tried another way:
FILE* pipe = popen("sleep 20 &", "r");
if(pipe){
char buffer[128];
while(fgets(buffer, 128, pipe));
cout<<buffer<<endl;
pclose(pipe);
}
This hangs for 20 seconds and i will never get that cout printed with the process id.
> ./a.out
>
Again I tried another way:
if(p=fork()){
//Main process
cout<<p<<endl;
}
else{
system("sleep 20 &");
}
}
> ./a.out
27464
> ps
PID TTY TIME CMD
27466 pts/52 0:00 sleep
27467 pts/52 0:00 ps
6746 pts/52 0:02 tcsh
Now you can see sleep running in the background but with different PID.
But what i need is the actual pid of the sleep command that is executed in the background. I strongly believe that there should be some way to get the exact pid of the process running in the background in c++. Could anybody please help?