在 Linux 系统中,确实可以通过创建子进程来执行函数。以下是几种常见的方法:
#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;
}
#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;
}
#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;
}
#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;
}
您需要哪种具体实现方式?或者您有特定的使用场景需要讨论吗?