创建两个子进程并打印进程树
时间: 2023-07-04 20:10:24 浏览: 68
下面是使用 Python 的 `os` 模块创建两个子进程并打印进程树的示例代码:
```python
import os
# 创建第一个子进程
pid1 = os.fork()
if pid1 == 0:
# 在子进程中
print("Child 1: pid={}, ppid={}".format(os.getpid(), os.getppid()))
# 创建第二个子进程
pid2 = os.fork()
if pid2 == 0:
# 在第二个子进程中
print("Child 2: pid={}, ppid={}".format(os.getpid(), os.getppid()))
else:
# 在第一个子进程中
os.waitpid(pid2, 0) # 等待第二个子进程结束
else:
# 在父进程中
os.waitpid(pid1, 0) # 等待第一个子进程结束
print("Parent: pid={}, ppid={}".format(os.getpid(), os.getppid()))
```
输出结果如下:
```
Child 1: pid=1234, ppid=1233
Child 2: pid=1235, ppid=1234
Parent: pid=1233, ppid=1232
```
相关问题
linux 创建两个进程
要在 Linux 中创建两个进程,可以使用 fork() 系统调用。fork() 调用会复制当前进程,创建一个新的子进程,这两个进程都从 fork() 调用之后开始执行。子进程的 PID(进程 ID)是通过 fork() 调用返回的值来获取的。下面是一个简单的示例代码,可以创建两个进程:
```
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程代码
printf("This is child process, PID = %d\n", getpid());
} else if (pid > 0) {
// 父进程代码
printf("This is parent process, child PID = %d\n", pid);
} else {
// 出错处理
printf("Error: fork() failed!\n");
}
return 0;
}
```
在上面的代码中,使用 fork() 创建了一个子进程,然后通过判断 fork() 返回值的大小来确定当前代码运行在父进程还是子进程中。在子进程中,通过 getpid() 函数获取自己的 PID。在父进程中,通过打印 fork() 返回的 PID 值来获取子进程的 PID。当 fork() 调用失败时,会返回 -1,此时需要进行错误处理。
Linux怎么创建两个进程
Linux可以使用fork()系统调用来创建子进程。fork()会将当前进程复制一份,生成一个新的子进程。新的子进程与原进程完全一致,包括进程的代码、数据、堆栈等。在新的子进程中,fork()返回值为0,表示该进程是子进程;在原进程中,fork()返回值为子进程的进程ID,表示该进程是父进程。
以下是一个创建两个进程的例子:
```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid1, pid2;
pid1 = fork(); // 创建第一个子进程
if (pid1 < 0)
{
printf("fork error\n");
exit(1);
}
else if (pid1 == 0) // 子进程1
{
// do something
printf("Child process 1\n");
exit(0);
}
else // 父进程
{
pid2 = fork(); // 创建第二个子进程
if (pid2 < 0)
{
printf("fork error\n");
exit(1);
}
else if (pid2 == 0) // 子进程2
{
// do something
printf("Child process 2\n");
exit(0);
}
else // 父进程
{
printf("Parent process\n");
// wait for child process to exit
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
}
}
return 0;
}
```
这个例子中,父进程创建了两个子进程,分别执行不同的任务。等待两个子进程执行完毕后,父进程才会继续执行。