Neji
Neji

Reputation: 6839

AOSP : how to get uid of given package name in c?

I want to get the UID of an application, I have the applications package name and I want it in C.

Are there any API that returns the UID related with given package in source? In what class and what are its requirements then?

Upvotes: 2

Views: 4201

Answers (3)

auselen
auselen

Reputation: 28087

You can do this in Java with Process.myUid().

On native, you can use getuid(), when including unistd.h and sys/types.h.

If you want to get it for another application, use PackageManager and see this answer on SO.

In general read this Unix question about UIDs. and GIDs

Upvotes: 2

Kevin Liu
Kevin Liu

Reputation: 1643

pid_t pid;
char args[4096], path[4096];

uid = getuid();

snprintf(path, sizeof(path), "/proc/%u/cmdline", pid);
fd = open(path, O_RDONLY);
if (fd < 0) {
    return -1; 
}   
len = read(fd, args, sizeof(args));
err = errno;
close(fd);
if (len < 0 || len == sizeof(args)) {
    return -1; 
}   

printf("The package name is %s\n", args);

Upvotes: 1

Robin
Robin

Reputation: 10368

You can refer to the system standard 'PS' implementation. The package name is the cmdline in procfs.

The complete code is at https://android.googlesource.com/platform/system/core/+/master/toolbox/ps.c

I think the code might be like:

iterate the proc/pid/cmdline find the pid first and then do something like this:

sprintf(statline, "/proc/%d/stat", pid);
struct stat stats;
stat(statline, &stats);
uid = stats.st_uid

Upvotes: 1

Related Questions