Professional Web Applications Themes

How to get the pid of a process from his name (in C) - Mac Programming

"ps -aux" give the name of an open application. How to get the pid of a such application from the application file name (or path) ?...

  1. #1

    Default How to get the pid of a process from his name (in C)

    "ps -aux" give the name of an open application.
    How to get the pid of a such application from the application file name
    (or path) ?
    Alain Guest

  2. #2

    Default Re: How to get the pid of a process from his name (in C)

    In article <168.1.3>, ca (Alain Birtz)
    wrote:
     

    Your question doesn't make sense, because there could be any number of such
    pids. What are you trying to do?

    meeroh

    --
    If this message helped you, consider buying an item
    from my wish list: <http://web.meeroh.org/wishlist>

    Miro Guest

  3. #3

    Default Re: How to get the pid of a process from his name (in C)

    I found many source for it but all are redirecting the output of "ps -aux".
    Someone tell me that there is linux toll called "pidof"
    It seem that ps scan /proc to found process info.
    I will take a look into ps.c...

    Thank you.


    In article <mit.edu>, Miro
    Jurisic <org> wrote:
     
    >
    > Your question doesn't make sense, because there could be any number of such
    > pids. What are you trying to do?
    >
    > meeroh[/ref]
    Alain Guest

  4. #4

    Default Re: How to get the pid of a process from his name (in C)

    In article <168.1.3>, ca (Alain Birtz)
    wrote:
     

    What are you trying to accomplish?

    meeroh

    --
    If this message helped you, consider buying an item
    from my wish list: <http://web.meeroh.org/wishlist>

    Miro Guest

  5. #5

    Default Re: How to get the pid of a process from his name (in C)

    Sending a SIGUSR1 signal to an other application by
    kill(pid of the other application, SIGUSR1)
    But I solve the problem by using shared memory.

    Thank you.
    In article <mit.edu>, Miro
    Jurisic <org> wrote:
     
    >
    > What are you trying to accomplish?
    >
    > meeroh[/ref]
    Alain Guest

  6. #6

    Default Re: How to get the pid of a process from his name (in C)

    /************************************************** ***
    * GetPIDForProcessName
    ************************************************** ***
    * Purpose: This functions purpose is to lookup a BSD
    * process PID given the BSD process name
    *
    * Parameters:
    * ProcessName A constant string. This
    * is the BSD process name used to do the process lookup. Note that
    * the process name you need to use is the name of the BSD executable
    * process. This is often the name of the BSD executable inside an
    * application bundle. In any case youcan find the BSD process name
    * of any process using the command "ps -xcocommand,pid" in terminal.
    *
    * ProcessPID A pointer to a pre-allocated pid_t. This
    * variable represents the data returned from the GetPIDForProcessName
    command.
    * On function success this value will contain a PID for the matching
    process
    * name requested. Note that if there are multiple processes with the
    same
    * name then the first matching process will be returned.
    * On function failure this variable will have the value zero.
    *
    * SysctlError A pointer to a pre-allocated integer. This
    * variable represents the error returned from the sysctl command. On
    function
    * success this variable will have a value specified by the sysctl based
    on the
    * error that occurred. On success the variable will have the value
    zero.
    * Note this variable can also be NULL in which case the variable is
    ignored.
    *
    * *Function Result* A integer return value.
    * See result codes listed below.
    * Result Codes:
    * 0 Success. Process PID was found and is located in
    * the ProcessPID variable.
    * -1 The requested process does not exist.
    * -2 Invalid process name passed (null value)
    * -3 Unable to get the size of sysctl buffer required
    * (consult SysctlError return value for more information)
    * -4 Unable to allocate memory to store BSD process
    information
    * (consult SysctlError return value for more information)
    *
    ************************************************** ***/
    int GetPIDForProcessName(const char* ProcessName, pid_t* ProcessPID,
    int* SysctlError)
    {
    const int kFoundRequestedProcess = 0;
    const int kCouldNotFindRequestedProcess = -1;
    const int kInvalidArgumentsError = -2;
    const int kErrorGettingSizeOfBufferRequired = -3;
    const int kUnableToAllocateMemoryForBuffer = -4;

    int mib[6];
    size_t sizeOfBufferRequired = 0; //set to zero to start with.
    int error = 0;
    int SuccessfullyGotProcessInformation;
    long NumberOfRunningProcesses = 0;
    int Counter = 0;
    struct kinfo_proc* BSDProcessInformationStructure = NULL;
    pid_t CurrentExaminedProcessPID = 0;
    char* CurrentExaminedProcessName = NULL;

    // --- Checking input arguments for validity --- //
    if (ProcessName == NULL)
    {
    return(kInvalidArgumentsError);
    }

    //--- Setting return values to known values --- //
    *ProcessPID = 0;

    if (SysctlError != NULL) //only set sysctlError if it is present
    {
    *SysctlError = 0;
    }

    /* Setting up the mib (Management Information Base) which is an
    array of integers where each
    * integer specifies how the data will be gathered. Here we are
    setting the MIB
    * block to lookup the information on all the BSD processes on
    the system. Also note that
    * every regular application has a recognized BSD process
    accociated with it. We pass
    * CTL_KERN, KERN_PROC, KERN_PROC_ALL to sysctl as the MIB to
    get back a BSD structure with
    * BSD process information in it (including BSD process names)
    */
    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_ALL;

    /* Here we have a loop set up where we keep calling sysctl until
    we finally get an unrecoverable error
    * (and we return) or we finally get a succesful result. Note
    with how dynamic the process list can
    * be you can expect to have a failure here and there since the
    process list can change between
    * getting the size of buffer required and the actually filling
    that buffer.
    */
    SuccessfullyGotProcessInformation = 0;

    while (SuccessfullyGotProcessInformation == 0)
    {
    /* Now that we have the MIB for looking up process
    information we will pass it to sysctl to get the
    * information we want on BSD processes. However, before we
    do this we must know the size of the buffer to
    * allocate to accomidate the return value. We can get the
    size of the data to allocate also using the
    * sysctl command. In this case we call sysctl with the
    proper arguments but specify no return buffer
    * specified (null buffer). This is a special case which
    causes sysctl to return the size of buffer required.
    *
    * First Argument: The MIB which is really just an array of
    integers. Each integer is a constant
    * representing what information to gather from the
    system. Check out the man page to know what
    * constants sysctl will work with. Here of course we
    pass our MIB block which was passed to us.
    * Second Argument: The number of constants in the MIB
    (array of integers). In this case there are three.
    * Third Argument: The output buffer where the return value
    from sysctl will be stored. In this case
    * we don't want anything return yet since we don't yet
    know the size of buffer needed. Thus we will
    * pass null for the buffer to begin with.
    * Forth Argument: The size of the output buffer required.
    Since the buffer itself is null we can just
    * get the buffer size needed back from this call.
    * Fifth Argument: The new value we want the system data to
    have. Here we don't want to set any system
    * information we only want to gather it. Thus, we pass
    null as the buffer so sysctl knows that
    * we have no desire to set the value.
    * Sixth Argument: The length of the buffer containing new
    information (argument five). In this case
    * argument five was null since we didn't want to set
    the system value. Thus, the size of the buffer
    * is zero or NULL.
    * Return Value: a return value indicating success or
    failure. Actually, sysctl will either return
    * zero on no error and -1 on error. The errno UNIX
    variable will be set on error.
    */
    error = sysctl(mib, 3, NULL, &sizeOfBufferRequired, NULL,
    NULL);

    /* If an error occurred then return the accociated error.
    The error itself actually is stored in the UNIX
    * errno variable. We can access the errno value using the
    errno global variable. We will return the
    * errno value as the sysctlError return value from this
    function.
    */
    if (error != 0)
    {
    if (SysctlError != NULL)
    {
    *SysctlError = errno; //we only set this variable
    if the pre-allocated variable is given
    }

    return(kErrorGettingSizeOfBufferRequired);
    }

    /* Now we successful obtained the size of the buffer
    required for the sysctl call. This is stored in the
    * SizeOfBufferRequired variable. We will malloc a buffer
    of that size to hold the sysctl result.
    */
    BSDProcessInformationStructure = (struct kinfo_proc*)
    malloc(sizeOfBufferRequired);

    if (BSDProcessInformationStructure == NULL)
    {
    if (SysctlError != NULL)
    {
    *SysctlError = ENOMEM; //we only set this variable
    if the pre-allocated variable is given
    }

    return(kUnableToAllocateMemoryForBuffer);
    //unrecoverable error (no memory available) so give up
    }

    /* Now we have the buffer of the correct size to hold the
    result we can now call sysctl
    * and get the process information.
    *
    * First Argument: The MIB for gathering information on
    running BSD processes. The MIB is really
    * just an array of integers. Each integer is a
    constant representing what information to
    * gather from the system. Check out the man page to
    know what constants sysctl will work with.
    * Second Argument: The number of constants in the MIB
    (array of integers). In this case there are three.
    * Third Argument: The output buffer where the return value
    from sysctl will be stored. This is the buffer
    * which we allocated specifically for this purpose.
    * Forth Argument: The size of the output buffer (argument
    three). In this case its the size of the
    * buffer we already allocated.
    * Fifth Argument: The buffer containing the value to set
    the system value to. In this case we don't
    * want to set any system information we only want to
    gather it. Thus, we pass null as the buffer
    * so sysctl knows that we have no desire to set the
    value.
    * Sixth Argument: The length of the buffer containing new
    information (argument five). In this case
    * argument five was null since we didn't want to set
    the system value. Thus, the size of the buffer
    * is zero or NULL.
    * Return Value: a return value indicating success or
    failure. Actually, sysctl will either return
    * zero on no error and -1 on error. The errno UNIX
    variable will be set on error.
    */
    error = sysctl(mib, 3, BSDProcessInformationStructure,
    &sizeOfBufferRequired, NULL, NULL);

    //Here we successfully got the process information. Thus
    set the variable to end this sysctl calling loop
    if (error == 0)
    {
    SuccessfullyGotProcessInformation = 1;
    }
    else //failed getting process information
    {
    /* The attempted sysctl call failed. We will now begin
    again by freeing up the allocated buffer and
    * returning a new buffer (likely of a different size).
    Also we will attempt to get
    * the process information once again with another call
    to sysctl. Note with the dynamic process
    * list you can expect failures here from time to time.
    */
    free(BSDProcessInformationStructure);
    }
    }//end while loop

    /* Now that we have the BSD structure describing the running
    processes we will p it for the desired
    * process name. First we will the number of running processesy.
    We can determine
    * the number of processes running because there is a kinfo_proc
    structure for each process.
    */
    NumberOfRunningProcesses = sizeOfBufferRequired / sizeof(struct
    kinfo_proc);

    /* Now we will go through each process description checking to see
    if the process name matches that
    * passed to us. The BSDProcessInformationStructure has an array of
    kinfo_procs. Each kinfo_proc has
    * an extern_proc accociated with it in the kp_proc attribute. Each
    extern_proc (kp_proc) has the process name
    * of the process accociated with it in the p_comm attribute and the
    PID of that process in the p_pid attibute.
    */
    for (Counter = 0 ; Counter < NumberOfRunningProcesses ; Counter++)
    {
    //Getting PID of process we are examining
    CurrentExaminedProcessPID =
    BSDProcessInformationStructure[Counter].kp_proc.p_pid;

    //Getting name of process we are examining
    CurrentExaminedProcessName =
    BSDProcessInformationStructure[Counter].kp_proc.p_comm;

    if ((CurrentExaminedProcessPID > 0) //Valid PID
    && ((strncmp(CurrentExaminedProcessName, ProcessName,
    MAXCOMLEN) == 0))) //name matches
    {
    *ProcessPID = CurrentExaminedProcessPID;
    free(BSDProcessInformationStructure);
    return(kFoundRequestedProcess);
    }
    }

    //if we got this far then we searched the entire process list and
    didn't find a matching process
    if (BSDProcessInformationStructure != NULL)
    free(BSDProcessInformationStructure);
    return(kCouldNotFindRequestedProcess);
    }

    --
    Mike Cohen - mike3k <at> onepost <dot> net
    Personal: http://www.mc-development.com/
    Mac News: http://www.macmegasite.com/
    Mike Guest

  7. #7

    Default Re: How to get the pid of a process from his name (in C)

    In article <bellsouth.net>,
    Mike Cohen <com> wrote:
     

    Please do not use this code in your product. There is a reason both kinfo_proc
    and extern_proc are inside #if __APPLE_API_UNSTABLE, not to mention the fact
    that it only works for processes whose name is shorter than 16 characters.

    meeroh

    --
    If this message helped you, consider buying an item
    from my wish list: <http://web.meeroh.org/wishlist>

    Miro Guest

  8. #8

    Default Re: How to get the pid of a process from his name (in C)

    There is some code at: http://developer.apple.com/qa/qa2001/qa1123.html

    In article <168.1.3>, ca (Alain
    Birtz) wrote:
     
    Alain Guest

  9. #9

    Default Re: How to get the pid of a process from his name (in C)

    In article <mit.edu>,
    Miro Jurisic <org> wrote:
     
    >
    > Please do not use this code in your product. There is a reason both
    > kinfo_proc
    > and extern_proc are inside #if __APPLE_API_UNSTABLE, not to mention the fact
    > that it only works for processes whose name is shorter than 16 characters.[/ref]

    Is there any alternative for someone who wants to use sysctl(3), which
    is useful for a whole lot more than just this one example? I'm using
    this function and a kinfo_proc in a couple of places, because I couldn't
    find any alternatives for getting the information I needed on Mac OS X.
    [In my case, in one place I needed to find all of a given process's
    sub-processes, and in another, I wanted the reverse of the example in
    this thread, i.e. get the process name associated with a given PID (and
    where I was only interested in the first 16 chars anyway).]

    Both times I did this, my code was substantially adapted from Apple demo
    code, at <http://developer.apple.com/qa/qa2001/qa1123.html> and
    <http://developer.apple.com/samplecode/Sample_Code/Platforms_and_Tools/PI
    DFromBSDProcessName/GetPID.c.htm>...

    --
    Tom "Tom" Harrington
    Macaroni, Automated System Maintenance for Mac OS X.
    Version 2.0: Delocalize, Repair Permissions, lots more.
    See http://www.atomicbird.com/
    Tom Guest

Similar Threads

  1. Replies: 9
    Last Post: March 8th, 11:36 PM
  2. Replies: 0
    Last Post: October 18th, 09:18 PM
  3. Replies: 6
    Last Post: May 17th, 07:08 PM
  4. Replies: 1
    Last Post: February 3rd, 09:30 AM
  5. Replies: 22
    Last Post: December 8th, 03:59 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139