?
Solved

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

Posted on 2002-07-16
11
Medium Priority
?
315 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
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
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
 

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 150 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever been frustrated by having to click seven times in order to retrieve a small bit of information from the web, always the same seven clicks, scrolling down and down until you reach your target? When you know the benefits of the command l…
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…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

864 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