Jump to content
  • Advertisement
Sign in to follow this  
ace84_84

C - Signals

This topic is 4592 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am new to the c and the c shell language. What I am learning is about signals and that stuff. I run my program, then i create a foreground process, and the foreground processes is my child, my problem is when i press 'ctrl + c', i want to send a signal to my child processes to terminate it, but when happens is that it usually terminates both the parent and the child processes. Do anyone know what i need to do???

void CTR_handler(int s)
{
	printf("Process %d got a CTR-C, exit\n", getpid());
	exit(0);
}

main()
{
   if((pid = fork()) == -1)
   {
         perror("Can not fork");
         exit(1);
   }

   if(pid > 0)
   {       // This is the parent
       if(!ampersand)   // Foreground execution
	{
		signal(2, CTR_handler);
              	waitpid(pid, 0, 0);
	}
	else
	{
	}
   }
   else
   {            // this is the child

	if(!ampersand)   
	{
				
	        if(execvp(argList[0], argList)==-1)
	    	{
                	perror("child Process");
                	exit(2);
            	}
			}
		else
		{
			setpgid(0, getpid());
			
			if ( (pid = fork() ) == 0 )//child
				execvp(argList[0], argList);
 			else
   				waitpid(pid, 0, 0);				
	   }
   }//end if
}//end main


Share this post


Link to post
Share on other sites
Advertisement
Lemme clean that up, and then give it a stare...


void CTR_handler(int s) {
printf("Process %d got a CTR-C, exit\n", getpid());
exit(0);
}

main() {

if( -1 == (pid = fork()) ) {
perror("Can not fork");
exit(1);
}

if( pid > 0 ) {
// This is the parent
if( ! ampersand ) {
// Foreground execution
signal(2, CTR_handler);
waitpid(pid, 0, 0);
} else { }

} else {
// this is the child
if( ! ampersand ) {
if( execvp(argList[0], argList) == -1 ) {
perror("child Process");
exit(2);
}

} else {
setpgid(0, getpid());

if ( 0 == (pid = fork() ) ) // child
execvp(argList[0], argList);
else
waitpid(pid, 0, 0);
}
}



Now, I'm gonna assume that all compiles and validates fine, because it's pretty darn ugly C as it is.

First off, your parameter order to setpgid is wrong; it's process first, then the new process group id.

Second, what assumptions are you making about which process acquires foreground? I can't see any such assumptions stated in the documentation for fork()...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!