首页 文章

fork()子进程和父进程

提问于
浏览
6

我正在尝试创建一个使用fork()来创建新进程的程序 . 示例输出应如下所示:

这是子进程 . 我的pid是733,我父母的id是772 .
这是父进程 . 我的pid是772,我孩子的id是773 .

这就是我编写程序的方式:

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), fork());

    return 0;
}

这导致输出:

这是子进程 . 我的pid是22163,我父母的id是0 .
这是子进程 . 我的pid是22162,我父母的id是22163 .

为什么它会两次打印语句?如何在第一句中显示子ID后如何正确显示父语句?

编辑:

#include <stdio.h>
#include <stdlib.h>

int main() {
int pid = fork();

if (pid == 0) {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
else {
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid);
}

return 0;
}

5 回答

  • 2

    它正在打印语句两次,因为它正在为父项和子项打印它 . 父级的父ID为0

    尝试这样的事情:

    pid_t  pid;
     pid = fork();
     if (pid == 0) 
        printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
     else 
        printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );
    
  • 0

    它打印两次是因为你正在调用printf两次,一次是在你的程序执行中,一次是在fork中 . 尝试从printf调用中取出fork() .

  • 0

    首先阅读fork man page以及getppid / getpid手册页 .

    从叉子

    成功时,子进程的PID在父进程的执行中返回,并在子进程的执行中返回0 . 失败时,将在父上下文中返回-1,不会创建子进程,并且将正确设置errno .

    所以这应该是一些事情

    if ((pid=fork())==0){
        printf("yada yada %u and yada yada %u",getpid(),getppid());
    }
    else{ /* avoids error checking*/
        printf("Dont yada yada me, im your parent with pid %u ", getpid());
    }
    

    至于你的问题:

    这是子进程 . 我的pid是22163,我父母的id是0.这是子进程 . 我的pid是22162,我父母的id是22163 .

    fork()printf 之前执行 . 因此,当它完成时,您有两个具有相同指令的进程 . 因此,printf将执行两次 . 对 fork() 的调用将返回 0 到子进程,子进程的 pid 将返回到父进程 .

    您将获得两个正在运行的进程,每个进程都将执行此指令语句:

    printf ("... My pid is %d and my parent's id is %d",getpid(),0);
    

    printf ("... My pid is %d and my parent's id is %d",getpid(),22163);
    

    要包装它,上面的行是子,指定它的 pid . 第二行是父进程,指定其id(22162)及其子(22163) .

  • 12

    这是获取正确输出的正确方法....但是,childs parent id有时可能打印为1,因为父进程终止,而pid = 1的根进程控制此孤立进程 .

    pid_t  pid;
     pid = fork();
     if (pid == 0) 
        printf("This is the child process. My pid is %d and my parent's id 
          is %d.\n", getpid(), getppid());
     else 
         printf("This is the parent process. My pid is %d and my parent's 
             id is %d.\n", getpid(), pid);
    
  • 0

    我们通过if,else语句控制fork()进程调用 . 请参阅下面的代码:

    int main()
    {
       int forkresult, parent_ID;
    
       forkresult=fork();
       if(forkresult !=0 )
       {
            printf(" I am the parent my ID is = %d" , getpid());
            printf(" and my child ID is = %d\n" , forkresult);
       }
       parent_ID = getpid();
    
       if(forkresult ==0)
          printf(" I am the  child ID is = %d",getpid());
       else
          printf(" and my parent ID is = %d", parent_ID);
    }
    

相关问题