Linux的进程创建
时间: 2024-02-24 18:52:27 浏览: 32
Linux中的进程创建可以使用fork函数或vfork函数。
1 使用fork函数创建进程[^1]:
```c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid == 0) {
// 子进程
printf("This is the child process\n");
} else {
// 父进程
printf("This is the parent process\n");
}
return 0;
}
```
运行上述代码,将会创建一个子进程。子进程中的pid为0,父进程中的pid为子进程的ID。
2. 使用vfork函数创建进程:
```c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = vfork();
if (pid < 0) {
fprintf(stderr, "Vfork failed");
return 1;
} else if (pid == 0) {
// 子进程
printf("This is the child process\n");
} else {
// 父进程
printf("This is the parent process\n");
}
return 0;
}
```
vfork函数与fork函数类似,但是它不会复制父进程的地址空间,而是与父进程共享地址空间。因此,在vfork函数中,子进程必须立即调用exec函数来执行新的程序。