Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a process whose pid keeps changing?

I know I can use the trick if (fork()) exit(0); to change the pid of the current process. So, the following program would have a pid changing very quickly. How to kill a process like this? Is there some better method than executing a lot of killall procname until one get able to run kill() before it forks? I know it is not a 'process', but many processes that run for a few microseconds each.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    pid_t self = getpid();
    while (1)
    {
        if (fork()) exit(0);
        if (self + 10000 < getpid()) break; // Just to kill it after some time
        usleep(1000);
    }
    return 0;
}

Also the only way I found to list the process was executing ps -A | grep procname a few times until one showed some output. Why isn't the process always listed?

like image 556
Guilherme Bernal Avatar asked Dec 01 '12 00:12

Guilherme Bernal


People also ask

Does PID always change?

PIDs will never change.

Which command will you issue to kill a process with PID?

There are two commands used to kill a process: kill – Kill a process by ID. killall – Kill a process by name.

Can PID of a process change?

Two processes cannot share a PID, but PID values may be reused. The PID does not change during the lifetime of a process. A different PID is a different process.


1 Answers

Such a process is called a "comet" by systems administrators.

The process group ID (PGID) doesn't change on fork, so you can kill it (or SIGSTOP it) by sending a signal to the process group (you pass a negated PGID instead of a PID to kill).

like image 165
caf Avatar answered Sep 18 '22 12:09

caf