Solved

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

Posted on 2002-07-16
11
304 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Software required to mount Linux LVM Volume 6 389
„dd“ vs „ddrescue“ 28 213
Getting permission denied on linux running a script 3 66
Help with Ubuntu 14.04 LTS 10 132
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 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…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Edureka is one of the fastest growing and most effective online learning sites.  We are here to help you succeed.

911 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

22 Experts available now in Live!

Get 1:1 Help Now