插件窝 干货文章 linux可以通过子进程执行函数吗

linux可以通过子进程执行函数吗

PID include 进程 return 690    来源:    2025-04-16

Linux 子进程执行函数的方法

在 Linux 系统中,确实可以通过创建子进程来执行函数。以下是几种常见的方法:

1. 使用 fork() + 函数调用

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

void my_function() {
    printf("This is executed in child process (PID: %d)\n", getpid());
}

int main() {
    pid_t pid = fork();

    if (pid == 0) { // 子进程
        my_function();
        _exit(0); // 子进程结束
    } else if (pid > 0) { // 父进程
        printf("Parent process (PID: %d) created child (PID: %d)\n", getpid(), pid);
    } else {
        perror("fork failed");
        return 1;
    }

    return 0;
}

2. 使用 posix_spawn()

#include <stdio.h>
#include <spawn.h>
#include <sys/wait.h>

extern char **environ;

void child_function() {
    printf("Child process executing\n");
}

int main() {
    pid_t pid;
    char *argv[] = {"./program", NULL};

    if (posix_spawn(&pid, "./program", NULL, NULL, argv, environ) != 0) {
        perror("posix_spawn failed");
        return 1;
    }

    printf("Parent process spawned child %d\n", pid);
    waitpid(pid, NULL, 0);

    return 0;
}

3. 使用 exec 系列函数

#include <stdio.h>
#include <unistd.h>

int main() {
    pid_t pid = fork();

    if (pid == 0) { // 子进程
        execl("/path/to/executable", "executable", "arg1", "arg2", NULL);
        perror("execl failed"); // 只有exec失败才会执行到这里
        _exit(1);
    } else if (pid > 0) {
        printf("Parent process, child PID: %d\n", pid);
    } else {
        perror("fork failed");
    }

    return 0;
}

4. 使用 clone() 系统调用 (更灵活)

#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define STACK_SIZE (1024 * 1024)

int child_function(void *arg) {
    printf("Child process in new namespace (PID: %d)\n", getpid());
    return 0;
}

int main() {
    char *stack = malloc(STACK_SIZE);
    if (!stack) {
        perror("malloc failed");
        return 1;
    }

    pid_t pid = clone(child_function, stack + STACK_SIZE, 
                     CLONE_NEWPID | SIGCHLD, NULL);

    if (pid == -1) {
        perror("clone failed");
        free(stack);
        return 1;
    }

    printf("Parent process, child PID: %d\n", pid);
    waitpid(pid, NULL, 0);
    free(stack);

    return 0;
}

注意事项

  1. 子进程会继承父进程的内存空间副本,但之后的修改互不影响
  2. 使用 fork() 时要注意资源管理,避免资源泄漏
  3. 子进程结束时应该使用 _exit() 而不是 exit(),以避免刷新父进程的缓冲区
  4. 在多线程程序中使用 fork() 要特别小心,最好只调用 async-signal-safe 函数

您需要哪种具体实现方式?或者您有特定的使用场景需要讨论吗?