Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ threads & infinite loop

I have a little problem, I wrote a program, server role, doing an infinite loop waiting for client requests.
But I would like this program to also return his pid.
Thus, I think I should use multithreading.
Here's my main :

int main(int argc, char **argv) {

    int pid = (int) getpid();
    int port = 5555

    ServerSoap *servsoap;
    servsoap = new ServerSoap(port, false);
    servsoap->StartServer(); //Here starts the infinite loop

    return pid; //so it never executes this
}

If it was bash scripting I would add & to run it in background.
Shall I use pthread ? And how to do it please ?

Thanks.
eo

like image 213
eouti Avatar asked Mar 25 '26 18:03

eouti


1 Answers

When a program returns (exits), all running threads terminate, so you can't have a background thread continue to run.

In addition, the int return value of main is (usually) truncated to a 7-bit value, so you don't have enough space to return a full pid.

It'd be better just to print the pid to stdout using printf.

like image 73
ecatmur Avatar answered Mar 28 '26 08:03

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!