Get ID of a process

Asked

Viewed 560 times

1

I wanted to get an ID of a process because I would like to use the kill() to send signals from a process to that. I know that to get the ID of the process itself is used getpid() however do not know how to get the ID of a process of which we only know the name. How can I do this ?

  • Which operating system?

  • If you can use C++ and it is Windows, you can get all the processes that are running with the function Enumprocesses, library Windows.h. Then just search for the name and kill.

  • 1

    @Renan Linux Ubuntu 14.04

  • In windows, if you know the process name you can use Kill directly by its name, example : taskkill /f /im Notepad.exe

1 answer

1

In linux, if there is no standard way to get PID from a process from its name, an interesting approach is to scan the directory /proc searching for all process-related Pids:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>


int obter_pids( const char * name, pid_t * pids, int * count )
{
    DIR * dir = NULL;
    struct dirent * ent = NULL;
    char * endptr = NULL;
    char buf[512] = {0};
    int i = 0;

    dir = opendir("/proc");

    if (!dir)
        return -1;

    while((ent = readdir(dir)) != NULL)
    {
        long lpid = strtol( ent->d_name, &endptr, 10 );

        if( *endptr != 0 )
            continue;

        snprintf( buf, sizeof(buf), "/proc/%ld/comm", lpid );

        FILE * fp = fopen(buf, "r");

        if( !fp )
            continue;

        if(fgets(buf, sizeof(buf), fp))
        {
            buf[strcspn(buf,"\n")] = 0;

            if( !strcmp( buf, name ) )
                pids[i++] = lpid;
        }

        fclose(fp);
    }

    closedir(dir);

    *count = i;

    return 0;
}


int main(int argc, char* argv[])
{
    int i = 0;
    pid_t pid[ 100 ];
    int count = 0;
    int ret = 0;

    if( argc != 2 )
    {
        printf("Sintaxe: %s NOME_DO_PROCESSO\n", argv[0]);
        return 1;
    }

    ret = obter_pids( argv[1], pid, &count );

    if( ret == -1 )
    {
        printf("Processo '%s' nao encontrado!\n", argv[1]);
        return 1;
    }

    for( i = 0; i < count; i++ )
        printf( "%d ", pid[i] );

    printf("\n");

    return 0;
}

Compiling:

$ gcc pidname.c -o pidname

Note that the same process can have n instances, which gives us a PID for each of them.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.