LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to determine if a program is running? (https://www.linuxquestions.org/questions/programming-9/how-to-determine-if-a-program-is-running-285669/)

iclinux 02-03-2005 03:18 AM

how to determine if a program is running?
 
I know the program's name and path.
how to implement it with c code?
Regards

xviddivxoggmp3 02-03-2005 03:23 AM

what are you talking about?
need more info to help.
if you want to see any active tasks you can use.

Code:

ps -al
check the man pages on ps.

i think this might be what you are looking for, but i'm not sure.

implement in c code?

you can run a system command to execute the ps command in the shell maybe.

are you writing a program that will be implimenting another program?

freeka 02-03-2005 04:58 AM

system("ps ax | grep UR-APP-NAME > /tmp/1337");
fopen("/tmp/1337", r);

then read out the file; if its empty u know program is not running

but this is a very ugly implementation

iclinux 02-03-2005 05:05 AM

xviddivxoggmp3,freeka, thank you.

I'm a new to Linux, is there any C fuctions that can do this?

freeka 02-03-2005 05:33 AM

not that i know of, but would be interesting. i think there exist a function in the kernel layer, dont know how to access and use it, i would be glad if someone can say somethin about it :>

however, i needed it in the past too, and wrote out of this implementation a crappy function by myself(but worked for me) which looked like this
Code:

/*
0 - is running
1 - is not running
2 - error
*/
int is_process_running(char *prozessname)
{
        FILE *fp;
        char system_call[200] = "ps ax | grep ";
        char buffer[100];

        remove("/tmp/is_p_run");

        strcat(system_call, prozessname);
        strcat(system_call, " > /tmp/is_p_run");

        system(system_call);

        if ((fp = fopen("/tmp/is_p_run", "r")) == NULL){
                perror("");
                return 2;
        }

        fgets(buffer,sizeof(buffer),fp);
        fgets(buffer,sizeof(buffer),fp);

        if((getc(fp)) != EOF){
                return 0;
        }
        return 1;
}


Hko 02-03-2005 06:13 AM

When it's not done in C entirely anyway (i.e. using system() or popen(),..), it's pobably easier/faster to use the "pidof" shell utility:
Code:

bash$ pidof init
1
bash$ pidof bash
6873 2751 2039 2035 2031


jlliagre 02-03-2005 11:26 AM

Although it will make your C code more complicated, you do not need to call a shell command from C to gather information about processes, you can instead directly browse the /proc filesystem.

Hko 02-03-2005 05:54 PM

Quote:

Originally posted by jlliagre
Although it will make your C code more complicated, you do not need to call a shell command from C to gather information about processes, you can instead directly browse the /proc filesystem.
I've tried iterating through /proc/<pid> to resolve the symlinks called "exe" to a full path, and then counting how many are the same string as a given path of an executable.

But if I'm not root, I have a lot of "permission denied revolving symlink"-like errors (through perror()). A regular user however can read /proc/<pid>/cmdline which contains (more or less) the name of the executable also. But this isn't accurate as it does not allways have the full path. Worse yet, programs can change argv[0] (I guess /proc/<pid>/cmdline == argv[0] ). And some programs actually do this. E.g. I've read somewhere sendmail does this.

Is it at all possible, for a regular user to see (accurately) if a given executable file is running?

keefaz 02-03-2005 06:09 PM

Did you look at /proc/<pid>/stat ?
The filename of the program is the second field between ( and )

iclinux 02-04-2005 03:00 AM

I don't konw how to do it gracefully.
There must be some APIs, but I don't know. Looking forward to your help.

Here are my code......


Code:

/************************************************************************/
/* Function Name : GetProcessID                                        */
/* Description  : get the ID of a specified process                    */
/* In            : pProcessName. name of the process,not case sensitive */
/*              : PidNum.      number of dwPID[]'s elements          */
/* Out          : PID.          conserve the process ID                */
/*              : PidNum.      hold the number of retrieved PID      */
/* Return        : true if succeeds; false if fails or process not exist*/
/* Note          : Get info from file "/proc/[PID]/stat",              */
/*                It contains contains pid,process name,etc.          */
/************************************************************************/
bool GetProcessID(const char *pProcessName, pid_t PID[], int &PidNum)
{
    char fullPath[PATH_MAX] = { 0 }; 
   
    const char *pdir =  "/proc/";  // Directory, ended with '/'
    const char *pFile = "/stat";  // File, contains pid,processname,etc.
   
    int pidnumber = 0;            // Conserve the pid number that matches
   
    DIR *dp = opendir(pdir);
    if (NULL == dp) return false;
   
    struct dirent *dirp = NULL;
    // Now traverse the directory
    while ((dirp=readdir(dp)) != NULL) { // Here, If has error, I ignore
       
        // Ignore current and parent directory
        if (strcmp(dirp->d_name, ".")==0 || strcmp(dirp->d_name, "..")==0) {
            continue;
        }
       
        // Get full path of the file or directory
        strncpy(fullPath, pdir, sizeof(fullPath) - 1);
        strncat(fullPath, dirp->d_name, sizeof(fullPath)-strlen(fullPath)-1);
       
        struct stat buf;
        int rtn = stat(fullPath, &buf);
        if (-1 == rtn) {
            continue; // Ignore if cannot get status
        }
       
        // There're many files, I care about the PID directory only
        if (S_ISDIR(buf.st_mode)) {
           
            if (atoi(dirp->d_name) <= 0) continue; // Not PID directory
           
            // Get the full path of the file that we need
            strncat(fullPath, pFile, sizeof(fullPath)-strlen(fullPath)-1);
           
            FILE *pfile = fopen(fullPath, "r");
            if (NULL == pfile) continue; // Ignore if cannot open
           
            int  procId = 0;
            char procName[512] = { 0 };
            char *pName = procName;
            // Get the info from the file
            fscanf(pfile, "%d%s", &procId, procName);
            fclose(pfile);
            // Get process name, eliminate the brackets '(' and ')'
            if (procName[0] == '(' && procName[strlen(procName)-1] == ')') {
                pName++;
                procName[strlen(procName) - 1] = '\0';
            }
           
            if (strcasecmp(pProcessName, pName) == 0  // Same process name
                && procId > 0)                        // Legal pid
            {
                if (pidnumber >= PidNum) break;                 
                else PID[pidnumber++] = procId;
            }
        }
    }
   
    closedir(dp);
   
    PidNum = pidnumber;
   
    if (0 == pidnumber)  // Not found
        return false;
    else
        return true;
}


iclinux 02-04-2005 03:12 AM

I forgot to say, I don't know how to get a process' full path.
And my fuction above is somewhat ugly...
Hope for your help
Regards


All times are GMT -5. The time now is 10:31 PM.