面试题答案
一键面试fork函数参数
fork
函数没有参数,其函数原型为:pid_t fork(void);
fork函数返回值含义
- 在父进程中:
fork
函数返回子进程的进程ID(PID)。子进程的PID是一个大于0的整数,通过这个返回值,父进程可以跟踪和管理子进程。 - 在子进程中:
fork
函数返回0。这使得子进程可以区分自己与父进程,因为只有子进程的返回值为0。 - 出错时:
fork
函数返回 -1。这通常表示系统资源不足,无法创建新的进程。
通过返回值判断父进程和子进程示例代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid;
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
printf("I am the child process. My PID is %d, my parent's PID is %d\n", getpid(), getppid());
} else {
// 父进程
printf("I am the parent process. My PID is %d. My child's PID is %d\n", getpid(), pid);
}
return 0;
}
在上述代码中,fork
函数被调用创建子进程。根据fork
函数的返回值判断当前进程是父进程还是子进程。如果返回值为 -1,表示出错;如果返回值为0,表示当前是子进程;如果返回值大于0,表示当前是父进程,且返回值为子进程的PID。