0

I have to stop the earlier instances of processes before starting a new instance. For this i need to system call or a C library call.

Presently i use "system("killall name"). This works but I want to replace this with any equivalent system(2)/library(3) calls. What is the option?

Also to remove files from directory as in "system("rm -f /opt/files*")", what would be the alternate library(3)/system(2) call? Pleas note * in file names, remove all files with one call.

regards, AK

Ashoka K
  • 453
  • 3
  • 6
  • 17

2 Answers2

2

As far as I know there is no general way to do it, as there is no general way to get the pid by its process name.

You have to collect the pids of related processes and call the int kill(pid_t pid, int signo); function

At least you can try to check how its implemented by killall itself


A small addition from Ben's link, killall invokes following lines, i.e. collecting the pids of related process by find_pid_by_name function, implementation of which can be found here

pidList = find_pid_by_name(arg);
if (*pidList == 0) {
    errors++;
    if (!quiet)
        bb_error_msg("%s: no process killed", arg);
} else {
    pid_t *pl;

    for (pl = pidList; *pl; pl++) {
        if (*pl == pid)
            continue;
        if (kill(*pl, signo) == 0)
            continue;
        errors++;
        if (!quiet)
            bb_perror_msg("can't kill pid %d", (int)*pl);
    }
}
deimus
  • 9,565
  • 12
  • 63
  • 107
  • 1
    And getting the list of processes is quite simple to code in C on Linux : `readdir` the `/proc/` file system. Focus on the subdirectories with a name starting with a digit. `readlink` its `/proc/1234/exe` symlink (where 1234 is an example of digit-starting name). – Basile Starynkevitch Apr 24 '15 at 14:00
  • 1
    Exactly, Erik Andersen has implemented the same way. http://git.busybox.net/busybox/tree/libbb/find_pid_by_name.c – deimus Apr 24 '15 at 14:10
2

You can see the implementation in busybox here: http://git.busybox.net/busybox/tree/procps/kill.c

You can also link with busybox as a shared library and invoke its kill_main instead of launching a separate process. It looks fairly well behaved for embedding like this -- always returns normally, never calls exit() -- although you may have difficultly getting error information beyond the return code. (But you aren't getting that via system() either).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720