Killing a background process from a C program

George Turczynski george at hls0.hls.oz
Wed Jul 25 12:02:21 AEST 1990


In article <7459 at amelia.nas.nasa.gov>, truong at wk35..nas.nasa.gov (Tuong C. Truong) writes:

> Just off the top of my head, but you may want to try something like :
> 
> set PID = `background_process&`
> 
> at this point PID will keep track of the process ID of the background process.
> later when you want to kill it, you may use something like:
> 
> kill -9 $PID
> 
> I have not tried this, but hope it works.

I have not tried this either, but I know it won't work.  That simply
isn't `C'.  The initial poster was writing in `C', and might get
very confused trying to use your solution :-)

Anyway, try something like this:


#include<stdio.h>
#include<signal.h>

#define	FOO_OK			0
#define	FOO_BAD_EXEC	1
#define FOO_BAD_FORK	2
#define FOO_BAD_KILL	3

int
foo(myname)
char *myname;	/* Perhaps equal to *argv[0]. */
{
    int pid;

    /* ... code ... */

    switch( pid= fork() )
    {
        case 0: /* execve() or execl etc. your child here. */
                /*
                 *	eg.
                 *
                 *	execl("/bin/cat","cat","/etc/passwd",(char *)0);
                 *
                 */

                 /* Should only get to here if exec?() fails. */

                 return FOO_BAD_EXEC;
		
        case -1: /* fork() failed. */

                 return FOO_BAD_FORK;
	
    }

    /* ... Parent code ... */

    if( kill(pid,SIGTERM) < 0 )
        return FOO_BAD_KILL;

    /* ... rest of code ... */

    return FOO_OK;

}

I humbly apologise for any typos in the above.  If anyone wants to
flame this, do it in aus.flame >please<.

Note:   kill() _will_ fail if the child has exited before kill() is
        called.

Note:   the use of "kill -9" is in VERY POOR TASTE with respect to
		unix.  "SIGTERM" (#15) is the software termination signal,
        so use it.

I hope this is of some benefit to the original poster, and to anyone
else watching.

Have a nice day...

George P. J. Turczynski           | ACSnet: george at highland.oz
System Administrator              | Phone: 61 48 683490
System Programmer                 | Fax:   61 48 683474
Logic Designer.                   |----------------------
Highland Logic Pty. Ltd.          | I can't speak for the
Suite 1, 348-354 Argyle Street    | company, I can barely
Moss Vale. NSW. 2577 Australia    | speak for myself...



More information about the Comp.unix.questions mailing list