Connecting Tech Pros Worldwide Forums | Help | Site Map

C++/Fork

Member
 
Join Date: Aug 2008
Location: South essex, England
Posts: 82
#1: Aug 28 '08
Hi, im working with fork, but I have a problem in this code:


Expand|Select|Wrap|Line Numbers
  1. int childp=0;
  2. int fork_return = fork();
  3. if(!fork_return){
  4. childp++;
  5.             cout << childp;
  6. }
when I run this, childp++ does nothing, the number is the same ( 0 ), every time.

Is there a way to get this to work?

Newbie
 
Join Date: Aug 2008
Posts: 3
#2: Aug 28 '08

re: C++/Fork


What the heck !!
It gives me 1 only
g++ compiler and on RHEL5
Member
 
Join Date: Aug 2008
Location: South essex, England
Posts: 82
#3: Aug 28 '08

re: C++/Fork


WTF!

What it is Im doing, Its a server, and im trying to limit the clients to 10,
And what I want is a value to increment when a client connects, and the value the decrement when the client disconnects.
so heres the basic code:

Expand|Select|Wrap|Line Numbers
  1. for(;;){
  2. sin_size = sizeof their_addr;
  3. clientsocket = accept(serversocket, (struct sockaddr *)&their_addr, &sin_size);
  4. if(childrun < CHILDS){
  5. if(!fork()){
  6. childrun++;
  7. {message.write("Client-"); message.write(childrun);  message.write(": connected.<br>\n");} 
  8. for(;;)
  9. {
  10. // the cient stuff 
  11. }
  12.  
  13. close(clientsocket);
  14. childrun--;
  15. message.write("::Client Disconnected.<br>\n");
  16. exit(0);
  17. }
  18. close(clientsocket);
  19. }
  20. }
  21.  
And the output is:

Client connected:--
::Sending welcome message: Sent
Server: Ping
Client-1: Pong.
Client-1: This is the first client
Client connected: --
::Sending welcome message: Sent.
Server: Ping
Client-1: Pong.
Client-1: <-- ??? this is the second client
Member
 
Join Date: Aug 2008
Location: South essex, England
Posts: 82
#4: Aug 28 '08

re: C++/Fork


So basicly, how can you change values in a fork/child, and the parent having that value.

so:

int a = 3;
if(!fork()){
a = 1;
}
cout << a; //a would still be 3.
Familiar Sight
 
Join Date: Apr 2007
Posts: 191
#5: Aug 28 '08

re: C++/Fork


I'm not sure what you guys expect. It might help for you to remember that when you fork() the parent and child each get their own copy of everything. So if the child changes his variable the parent won't see it (unless you set up some shared memory or something).

Does that help?
Member
 
Join Date: Aug 2008
Location: South essex, England
Posts: 82
#6: Aug 28 '08

re: C++/Fork


I guess I could use pointers.
gpraghuram's Avatar
Expert
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,258
#7: Aug 29 '08

re: C++/Fork


Since the parent and child have 2 different copies of the variable a you cant simply use the variable or pointer to accompolish this.
You should have a IPC to do this like PIPE or shared memory.


Thanks
Raghu
Reply


Similar C / C++ bytes