Awalias
Awalias

Reputation: 2137

Is there a way to print the PID of the process that called my C binary

I need to know which perl script is using my C CLI.

Using bash I can easily print "who" ran a script using:

CALLER=$(ps ax | grep "^ *$PPID" | awk '{print $NF}')
echo $CALLER

Up to now I have been using this as a wrapper but it's not ideal. Is there a way to get this information from within C?

(I'm running UNIX w/ gcc)

Upvotes: 5

Views: 30712

Answers (3)

pb2q
pb2q

Reputation: 59637

Use getppid. See man 2 getppid, here's the linux man page.

getppid() returns the process ID of the parent of the calling process

Two p’s because this is for the “parent process”.

Upvotes: 6

md5
md5

Reputation: 23727

You should look at getpid and getppid functions from <unistd.h>.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int
main(void)
{
    printf("%ld%ld", (long)getpid(), (long)getppid());
    return 0;
}

Upvotes: 12

hmjd
hmjd

Reputation: 122001

Use getppid() to obtain the process id of a process' parent.

Upvotes: 2

Related Questions