4
//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 ,我希望在程序执行结束后控制权转移到终端。

4

2 回答 2

9
#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 表示父进程,因此父进程和子进程同时运行访问相同的资源,因此出现竞争条件的问题。哪个是首先访问它首先执行的资源,另一个是稍后执行的。

等待函数避免竞争条件和当子执行完成时,直到父等待和执行父之后

默认 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 
于 2013-04-18T10:54:59.117 回答
7

并行过程的问题在于它们不能很好地映射到“先发生”的想法。它们并行运行。

当然,您可以通过在打印输出之前延迟父母的代码来改变赔率。

完全不确定“控制权转移到程序”是什么意思;因为这两个进程在打印它们的消息后都会很快命中exit(),所以应该没有程序可以转移控制权。

请注意,您不需要使用exit()from main(),它应该以普通 old 结尾,return因为它的返回类型是int.

于 2013-04-18T08:03:27.737 回答