Killing a background process from a C program

D Venkatrangan venkat at matrix.UUCP
Fri Jul 27 07:08:00 AEST 1990


In article <1990Jul19.151728.17448 at ncs.dnd.ca> marwood at ncs.dnd.ca (Gordon Marwood) writes:
>I am in the process of converting a Bourne shell script to C, and I am
>having trouble finding out how to identify and kill background
>processes.  With the Bourne Shell approach this was simple, using $!.
>
>What I would like to do is start a background process at one point in the
>C program, and at a later time kill it.  Currently I am invoking the
>background process with system("background_process &");, but none of the
>texts that I have available help me to proceed any further.
>
>Any assistance would be appreciated.
>

Instead of system(), try using vfork() followed by execlp().

In foreground program, do something like:

	if ((child_pid = vfork()) == -1)
		perror("vfork failed");

	if (child_pid == 0) {
		execlp(execfile, execfile, arg1, arg2, ..., (char *)0);
		/* should not return */
		perror("exec failed");
	}

	/* parent */

	/* if we get killed... */
	(void)signal(SIGINT, kill_child);

/* call kill_child() to send a user defined signal to child. */
/* or just call kill(child_pid, SIGUSR1); */

void
kill_child(sigval)
int sigval;
{
	if (sigval == SIGINT)
		kill(child_pid, SIGUSR1);
}

In child, during initialization do:

	(void)signal(SIGUSR1, childsighandler);


and define:

void
childsighandler(sigval)
int sigval;
{
	if (sigval == SIGUSR1) {	/* the parent is sending something */
		cleanup();
		exit();
	}
}


	



More information about the Comp.lang.c mailing list