我正在研究计算机系统,我已经创建了这个非常简单的函数,用于fork()创建子进程.如果它是子进程,则fork()返回pid_t0.但是getpid()在这个子进程中调用该函数会返回一个不同的非零pid.在我下面的代码中,newPid只在程序的上下文中有意义,而不是对操作系统有意义吗?它可能只是一个相对值,用父母的pid来衡量?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
void unixError(char* msg)
{
printf("%s: %s\n", msg, strerror(errno));
exit(0);
}
pid_t Fork()
{
pid_t pid;
if ((pid = fork()) < 0)
unixError("Fork error");
return pid;
}
int main(int argc, const char * argv[])
{
pid_t thisPid, parentPid, newPid;
int count = 0;
thisPid = getpid();
parentPid = getppid();
printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);
if ((newPid = Fork()) == 0) {
count++;
printf("I am the child. My pid is %d, my other pid is %d\n", getpid(), newPid);
exit(0);
}
printf("I am the parent. My pid is %d\n", thisPid);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
thisPid = 30050, parent pid = 30049
I am the parent. My pid is 30050
I am the child. My pid is 30052, my other pid is 0
Run Code Online (Sandbox Code Playgroud)
最后,为什么孩子的pid 2比父母的pid高,而不是1?main函数的pid和它的父元素之间的区别是1,但是当我们创建一个子元素时,它会将pid增加2.为什么呢?
从fork 手册页:
回报价值
成功时,子进程的PID在父进程中返回,并在子进程中返回0.失败时,在父项中返回-1,不创建子进程,并正确设置errno.
Fork不返回子项的pid,仅返回父项的pid.因此,子进程没有两个pid.
试试这个
int main(int argc, const char * argv[])
{
pid_t thisPid, parentPid, newPid;
int count = 0;
thisPid = getpid();
parentPid = getppid();
printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);
if ((newPid = Fork()) == 0) {
count++;
printf("I am teh child. My pid is %d\n", getpid());
exit(0);
}
else
printf("I am the parent. My pid is %d, my child pid is %d\n", thisPid, newPid);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2643 次 |
| 最近记录: |