/*
    pidof: return the pid of a named process - mini util made for
        early-userspace.
    Copyright (C) 2006, Aaron Griffin <aaronmgriffin@gmail.com>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <ctype.h>

int main(int argc, char **argv)
{
    DIR *d;
    struct dirent *dent;

    if (argc != 2)
    {
        fprintf(stderr, "usage: pidof processname\n");
        return 1;
    }

    if ((d = opendir("/proc")) == 0)
    {
        fprintf(stderr, "ERROR: could not open /proc\n");
        return 1;
    }

    while ((dent = readdir(d)) != 0)
    {
        char *p = 0;

        if (dent->d_name[0] == 0) continue;

        for (p = dent->d_name; *p; ++p)
            if (!isdigit(*p)) break;
        if (*p == 0)
        {
            FILE *f;
            char buf[BUFSIZ];

            sprintf(buf, "/proc/%s/status", dent->d_name);
            
            if ((f = fopen(buf, "r")) != 0)
            {
                while (fgets(buf, BUFSIZ, f) != 0)
                {
                    int len = strlen(buf);
                    if (buf[len-1] == '\n') buf[len-1] = 0;
                    if (strncasecmp(buf, "name:", 5) == 0)
                    {
                        for (p = buf+5; *p && isspace(*p); ++p) ;
                        printf("compare [%s]=[%s]\n",argv[1],p);
                        if (strcmp(argv[1], p) == 0)
                            puts(dent->d_name);
                        break;
                    }
                }
                fclose(f);
            }
        }
    }
    closedir(d);
    return 0;
}
