Sign in to follow this  
ace84_84

C - Signals

Recommended Posts

ace84_84    151
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
Wyrframe    2426
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this