在Linux中创建多个进程可以通过多种方式实现,以下是一些常见的基础概念和方法:
fork()
系统调用可以创建一个新的进程,新进程称为子进程,原进程称为父进程。子进程会复制父进程的内存空间和资源。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
// 创建进程失败
perror("fork failed");
return 1;
} else if (pid == 0) {
// 子进程
printf("子进程ID: %d
", getpid());
} else {
// 父进程
printf("父进程ID: %d
", getpid());
wait(NULL); // 等待子进程结束
}
return 0;
}
exec()
系列函数可以在当前进程中加载并运行一个新的程序,替换当前进程的镜像。
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
return 1;
} else if (pid == 0) {
// 子进程
execl("/bin/ls", "ls", "-l", NULL);
perror("execl failed"); // 如果execl返回,说明执行失败
return 1;
} else {
// 父进程
wait(NULL); // 等待子进程结束
}
return 0;
}
虽然线程不是进程,但它们可以用来实现并发执行。线程共享进程的资源,相比进程创建和销毁的开销更小。
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
printf("线程ID: %ld
", pthread_self());
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
通过以上方法和注意事项,可以在Linux中有效地创建和管理多个进程。
领取专属 10元无门槛券
手把手带您无忧上云