summaryrefslogtreecommitdiff
path: root/compositor.c
blob: 647061107d55e4c8d858c0c2be491f5be4286ceb (plain)
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
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wayland-client.h>
#include <sys/socket.h>
#include <errno.h>

#define PROCESS_NAME_MAX_LENGTH 1024

char name[PROCESS_NAME_MAX_LENGTH] = "";

static pid_t
pid_from_fd(int fd)
{
    struct ucred ucred;
    socklen_t len = sizeof(struct ucred);
    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1) {
        perror("getsockopt failed");
        exit(-1);
    }
    return ucred.pid;
}

static char *
process_name_from_pid(const pid_t pid) {
    char proc_buf[64];
    sprintf(proc_buf, "/proc/%d/comm", pid);
    FILE *fp;
    if ((fp = fopen(proc_buf, "r")) == NULL) {
        fprintf(stderr, "opening '%s' failed: %s\n", proc_buf, strerror(errno));
        exit(-1);
    }
    if (fgets(name, PROCESS_NAME_MAX_LENGTH, fp) == NULL) {
        fprintf(stderr, "reading '%s' failed\n", proc_buf);
        exit(-1);
    }
    name[strcspn(name, "\n")] = 0;
    fclose(fp);
    return name;
}

char *
process_name_from_fd(struct wl_display *display)
{
    int fd = wl_display_get_fd(display);
    pid_t pid = pid_from_fd(fd);
    char *process_name = process_name_from_pid(pid);
    return process_name;
}