//same program different code
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pid;
pid=fork();
if(pid<0)
{
printf("\n Error ");
exit(1);
}
else if(pid==0)
{
printf("\n Hello I am the child process ");
printf("\n My pid is %d ",getpid());
exit(0);
}
else
{
printf("\n Hello I am the parent process ");
printf("\n My actual pid is %d \n ",getpid());
exit(1);
}
}
我试过了,我希望它是正确的。
但我对输出不满意。
输出是:
Hello I am the parent process
My actual pid is 4287
ashu@ashu-VirtualWorld:~/Desktop/4thSemester/testprep$
Hello I am the child process
My pid is 4288
请帮助我,我无法理解它的输出,我希望子进程先出现,然后是父进程。 此外,当执行结束时,控制权转移到程序,因此要返回到终端,我必须使用 ctrl+c,我希望在程序执行结束后,控制权转移到终端。
最佳答案
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
int status;
int pid;
pid=fork();
if(pid<0)
{
printf("\n Error ");
exit(1);
}
else if(pid==0)
{
printf("\n Hello I am the child process ");
printf("\n My pid is %d ",getpid());
exit(0);
}
else
{
wait(&status);
printf("\n Hello I am the parent process ");
printf("\n My actual pid is %d \n ",getpid());
exit(1);
}
}
在此程序中,if (pid == 0) 表示子级,pid > 0 表示父级 parent 和 child 在同一时间运行并访问相同的资源,因此会出现竞争条件问题。 哪个首先访问其首先执行的资源,另一个是 稍后执行。
等待函数避免竞争条件和子执行完成时 直到父等待并在执行父之后
默认的 vfork 避免竞争条件
pid=vfork();
Because the vfork use the parent wait for until the child complete.
另外如果你想获得父进程的进程ID。使用 int ppid = getppid() 函数。
程序的输出是:
Hello I am the child process
My pid is 7483
Hello I am the parent process
My actual pid is 7482
关于c - 父进程创建子进程并且父进程和子进程运行相同程序不同代码的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077528/