Skip to content

Using pidfd instead of pid in WClient::pidFD #634

@zccrs

Description

@zccrs

This is an example:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/socket.h>  // for SO_PEERPIDFD
#include <signal.h>

int main() {
    int sv[2]; // Socket pair: sv[0] and sv[1]
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        perror("socketpair");
        exit(EXIT_FAILURE);
    }

    pid_t child = fork();
    if (child == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (child == 0) {
        // 子进程
        close(sv[0]); // 关闭父端
        pause();      // 保持进程存在
        exit(0);
    } else {
        // 父进程
        close(sv[1]); // 关闭子端

        int pidfd;
        socklen_t len = sizeof(pidfd);
        if (getsockopt(sv[0], SOL_SOCKET, SO_PEERPIDFD, &pidfd, &len) == -1) {
            perror("getsockopt SO_PEERPIDFD");
            exit(EXIT_FAILURE);
        }

        printf("Received pidfd = %d\n", pidfd);

        // 验证 pidfd 是否可用,例如:使用 pidfd_send_signal 测试
        if (pidfd_send_signal(pidfd, 0, NULL, 0) == 0) {
            printf("Process is alive (via pidfd_send_signal).\n");
        } else {
            perror("pidfd_send_signal");
        }

        close(pidfd);
        close(sv[0]);
        wait(NULL);
    }

    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions