Xref: utzoo comp.lang.c:30574 comp.unix.questions:24095 Path: utzoo!attcan!uunet!matrix!venkat From: venkat@matrix.UUCP (D Venkatrangan) Newsgroups: comp.lang.c,comp.unix.questions Subject: Re: Killing a background process from a C program Message-ID: <159@matrix.UUCP> Date: 26 Jul 90 21:08:00 GMT References: <1990Jul19.151728.17448@ncs.dnd.ca> Reply-To: venkat@matrix.UUCP (D Venkatrangan) Organization: Matrix Computer Systems Inc. Lines: 61 In article <1990Jul19.151728.17448@ncs.dnd.ca> marwood@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(); } }