Get ID of a process [closed]

1

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

    
asked by anonymous 06.05.2016 / 18:10

1 answer

1

In linux, if there is no standard way to get PID of a process from its name, an interesting approach is to scan the /proc directory 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

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

I hope I have helped!

    
06.05.2016 / 23:49