在Linux系统中创建进程和线程是系统编程中常见的需求。本文将详细介绍如何使用C语言在Linux环境下创建两个进程,每个进程中包含两个线程。
环境准备
在进行以下操作之前,请确保您的系统已经安装了GCC编译器和C语言开发环境。以下是具体步骤:
- 安装GCC:打开终端,使用以下命令安装GCC:
sudo apt-get update sudo apt-get install build-essential - 创建C语言源文件:在终端中创建一个名为
thread_process.c的文件。
创建进程和线程
1. 包含必要的头文件
在源文件的开头,包含必要的头文件:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
2. 定义线程函数
定义一个线程函数,该函数将在每个线程中执行:
void *threadFunction(void *arg) {
int thread_id = *(int *)arg;
printf("Thread %d is running\n", thread_id);
return NULL;
}
3. 创建线程
在主函数中,首先创建两个进程:
pid_t pid1, pid2;
pid1 = fork();
if (pid1 < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
pid2 = fork();
if (pid2 < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
然后,在每个进程中创建两个线程:
if (pid1 == 0) { // 子进程1
pthread_t threads[2];
for (int i = 0; i < 2; i++) {
int id = i + 1;
if (pthread_create(&threads[i], NULL, threadFunction, &id) != 0) {
perror("pthread_create failed");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
exit(EXIT_SUCCESS);
} else if (pid2 == 0) { // 子进程2
pthread_t threads[2];
for (int i = 0; i < 2; i++) {
int id = i + 3;
if (pthread_create(&threads[i], NULL, threadFunction, &id) != 0) {
perror("pthread_create failed");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
exit(EXIT_SUCCESS);
}
4. 等待子进程结束
在主进程中,使用 wait 或 waitpid 函数等待两个子进程结束:
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
5. 编译并运行程序
使用以下命令编译程序:
gcc -o thread_process thread_process.c -lpthread
然后运行程序:
./thread_process
您应该会看到以下输出:
Thread 1 is running
Thread 2 is running
Thread 3 is running
Thread 4 is running
这样,您就在Linux系统中成功创建了两个进程,每个进程中包含两个线程。希望本文能帮助您!
