演示如何使用C语言创建两个进程:
时间: 2024-04-30 21:22:26 浏览: 111
以下是使用C语言创建两个进程的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
// 创建第一个子进程
pid1 = fork();
if (pid1 < 0) {
fprintf(stderr, "Fork failed\n");
exit(1);
} else if (pid1 == 0) {
// 子进程1代码
printf("Child process 1 (pid: %d) is running.\n", getpid());
exit(0);
} else {
// 创建第二个子进程
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork failed\n");
exit(1);
} else if (pid2 == 0) {
// 子进程2代码
printf("Child process 2 (pid: %d) is running.\n", getpid());
exit(0);
} else {
// 父进程代码
printf("Parent process (pid: %d) is running.\n", getpid());
printf("Created child processes %d and %d.\n", pid1, pid2);
// 等待子进程结束
wait(NULL);
wait(NULL);
printf("All child processes have exited.\n");
exit(0);
}
}
}
```
该程序首先创建第一个子进程,然后在子进程1中输出一条消息并退出。接着,程序在父进程中创建第二个子进程,并在子进程2中输出一条消息并退出。最后,在父进程中等待两个子进程结束,输出一条消息并退出。
可以通过编译并运行该程序来查看输出结果。在Linux中,可以使用以下命令来编译该程序:
```
gcc -o fork_example fork_example.c
```
然后,可以运行该程序:
```
./fork_example
```
输出结果应该类似于以下内容:
```
Parent process (pid: 1234) is running.
Created child processes 1235 and 1236.
Child process 1 (pid: 1235) is running.
Child process 2 (pid: 1236) is running.
All child processes have exited.
```
阅读全文
相关推荐





