在Linux系统下,可以使用fork()函数来创建子进程。fork()函数会将当前进程复制一个子进程,子进程和父进程完全相同,包括代码,打开的文件,环境变量等等。子进程会从fork()函数返回处继续执行,而父进程也会继续执行,但fork()函数会返回子进程的进程ID。

具体实现可以参考下面的代码:
#include
#include
#include
int main() {
pid_t pid;
pid = fork(); // 创建子进程
if (pid < 0) {
printf("fork error.\n");
return 1;
} else if (pid == 0) {
// 子进程执行的代码
printf("This is child process. My PID is %d.\n", getpid());
} else {
// 父进程执行的代码
printf("This is parent process. My PID is %d, my child's PID is %d.\n", getpid(), pid);
}
return 0;
}

查看详情

查看详情