Solved

When will the returned value of fork() in child process has the 0 value?

Posted on 2002-07-16
11
303 Views
Last Modified: 2010-04-21
Hi,

In my code following here, I create a child process by calling fork().  I have some signal handler:
 - The child process will do some tasks when it receives a SIGALARM signal.
 - The child process will exit on receiving a SIGTERM.
 - If the parent process receives the SIGTERM it will forward to the child process then exit .

I use the same handler of SIGTERM (Terminate()) for both parent and child process. I use a global variable gpid(=fork()) to classify them.

If there's an error in the parent process, it sends a SIGTERM to the child process and exit.

My problem here is sometimes the child process receives a SIGTERM but its gpid is still -1.

Please help,
Thanks
===========================
pid_t gpid = -1;

void DoSomething()
{
     //Do some Child's things...
}

void Terminate(int a)
{
     if(gpid>0)  //ParentProcess
     {
          kill(gpid, SIGTERM);
          exit(0);
     }
     else if(gpid==0) //Child Process
     {
          //The Child process sometimes can't get here because gpid==-1
          _exit(0);
     }
}

void SetSignalHandler()
{
     struct sigaction act;
     
     act.sa_handler = SIG_IGN;
     sigemptyset(&act.sa_mask);
     act.sa_flags = SA_NOCLDSTOP||SA_NOCLDWAIT;
     
     if(sigaction(SIGCHLD, &act, NULL)<0)
     {
          cout<<"Error set signal handler"<<endl;
          exit(2);
     }

     act.sa_handler = DoSomething;
     sigemptyset(&act.sa_mask);
     act.sa_flags = 0;
     
     if(sigaction(SIGALRM, &act, NULL)<0)
     {
          cout<<"Error set signal handler"<<endl;
          exit(2);
     }
     
     act.sa_handler = Terminate;
     sigemptyset(&act.sa_mask);
     act.sa_flags = SA_RESTART;
     
     if(sigaction(SIGTERM, &act, NULL)<0)
     {
          cout<<"Error set signal handler"<<endl;
          exit(2);
     }    
}

int main()
{
     SetSignalHandler();

     gpid = fork();
     if(gpid ==-1)
     {
          cout<<"Error fork()"<<endl;
          exit(1);
     }
     else if(gpid==0)//Child process
     {
          alarm(50);
          while(1);
         
          _exit(0);
     }

     //Check for error in the Parent process
     //if(checkError())
     if(true)
     {
          kill(gpid, SIGTERM);
          exit(1);
     }

     //Do some Parent's things...
}
0
Comment
Question by:myduong
  • 6
  • 5
11 Comments
 
LVL 51

Expert Comment

by:ahoffmann
ID: 7158968
> .. sometimes the child process receives a SIGTERM but its gpid is still -1.

As I read the posted code, that could not be, 'cause the child code is only executed if gpid==0.
So you either check the gpid in a wrong place, or you overwrite it somewhere.

BTW, I recommend to set the SigHandler in the child process too (depending on the OS some systems reset all andlers to defaults in a forked process).
0
 

Author Comment

by:myduong
ID: 7159844
> .. sometimes the child process receives a SIGTERM but its gpid is still -1.

Could you explain in more details?

>As I read the posted code, that could not be, 'cause the child code is only executed if gpid==0.
So you either check the gpid in a wrong place, or you overwrite it somewhere.

I'm sure that I didn't ovwrwrite the gpid in the child process.  The problem may be because the child process had received the SIGTERM before its gpid was set to 0.  In this case, the client code didn't execute at all. (*)

>BTW, I recommend to set the SigHandler in the child process too (depending on the OS some systems reset all andlers to defaults in a forked process).

This is true.  But I'm just afraid that if my above(*) thought is true then the child process won't use my handler for SIGTERM. In the code I posted, it makes no different with the default handler for SIGTERM.  But actually, I have some more works for the child process before exiting.
0
 

Author Comment

by:myduong
ID: 7159863
...and if I change Terminate() like
void Terminate()
{
  cout<<gpid<<"-"<<getpid()<<endl;
...
}

I will receive an uncertain output.  Sometimes it's "0-xxx" but sometimes it's "-1-xxx"

xxx is the child process id.

The parent process always gives correct output like childpid-parentpid
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 7160436
try to add a:
    sleep(5);
in the parent right behind the
   if(gpid ==-1) { ... }
 
probaly the scheduler gives your parent the time slice first, so that it sends a kill to it's child before it has been executed any statement (except the fork itself).
0
 

Author Comment

by:myduong
ID: 7160729
I know that would work.  But it doesn't answer my real question (the title).  The parent process is a server which accept connections from many clients.  That's not a good solution.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:myduong
ID: 7160738
I know that would work.  But it doesn't answer my real question (the title).  The parent process is a server which accept connections from many clients.  That's not a good solution.
0
 
LVL 51

Accepted Solution

by:
ahoffmann earned 50 total points
ID: 7160775
except in a real-time OS, this question can only be answered as I already did:
  the behaviour is random
means that the kernel scheduler decides which process, parent or child, gets which time slice, and which one will be first.

Why did you kill the child from the parent?
If this is necessary for any reason, you need to implement either a reliable timeout, or a handshake between parent and child (for example: the child sends a signal to the parent when it detects gpid==0).
0
 

Author Comment

by:myduong
ID: 7160867
I kill the child from the parent because I want to do some cleanups and gracefully terminate connections with the clients.
Thanks for your comments anyway.
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 7160881
> .. do some cleanups ..
why not using SIGALRM with an alarm-handler in the child?
This alarm-handler may terminate the child on your conditions.
That  makes the child independent of the parent.
0
 

Author Comment

by:myduong
ID: 7162415
My program acts as both a server and a client. The server (parent process)accepts connections from clients and receives data.  The client (child process) connects to another server every x seconds (SIGALARM) and sends the data it received.
I have 2 processes because I don't want the incoming connections to be delayed while I'm sending information to the other server.
The child process will run forever unless I kill it.  And I want to have it gracefully disconnect the other server when it is killed. That's why I catch the SIGTERM in the parent process and send it to the child.
Am I doing it the right way?
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 7163348
sounds resonable
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

The purpose of this article is to fix the unknown display problem in Linux Mint operating system. After installing the OS if you see Display monitor is not recognized then we can install "MESA" utilities to fix this problem or we can install additio…
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now