POO*_*PTA 3 c operating-system fork
我试过实现一个os程序.这是代码:
#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
int main()
{
pid_t pid, pid1;
pid = fork();
if(pid<0)
{
fprintf(stderr,"Fork Failed");
return 1;
}
else if(pid == 0) /* child process */
{
pid1 = getpid();
printf("child: pid = %d\n",pid);
printf("child: pid1 = %d\n",pid1);
}
else /* parent process */
{
pid1 = getpid();
printf("parent: pid = %d\n",pid);
printf("parent: pid1 = %d\n",pid1);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
及其o/p:
parent: pid = 1836
parent: pid1 = 1835
child: pid = 0
child: pid1 = 1836
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下它是如何工作的,即代码中编写的if/ else-if/ else语句的执行顺序.我认为一旦else if条件变为真,那么else部分就不会被执行,但是在这里它执行了父进程部分即else部分然后是子部分.....为什么会这样?
你应该读一下fork().一旦你敲响了一个fork()语句,就会启动第二个进程,它有一个父进程拥有的所有东西的副本,但它可以运行一个单独的执行,它从中查看的返回与父进程看到的fork不同.
int main()
{
pid_t pid, pid1;
<--- up to here you have one process running
pid = fork(); <--- when this returns you have two processes:
parent has pid = child's pid child has pid = 0
if(pid<0) <--- child and parent both check this, it's not true so they move on
{
....
}
else if(pid == 0)<--- this is true for the child, not the parent
{
.... <--- child will now execute this code
}
else <-- nothing else was true for the parent so it sees this
.... <-- and executes this code
Run Code Online (Sandbox Code Playgroud)
所以,是的,你是正确的,一旦你打的if,或else if或else你不打算进入的代码的另一个分支,在一个单一的过程执行.你看到了else if,else因为你有两个进程在运行.
注意它们是如何pid1不同的,因为getpid()返回哪个进程正在运行该代码,你可以看到你有两个不同的进程,一个选择else if另一个选择else.