需要使用fork()函数实现条件输出的帮助

时间:2017-03-09 01:28:25

标签: c++

  • 在下面的程序中,我试图实现这些条件:
  • 我正在尝试只实现第一个子进程来打印“hi”?
  • 和打印“areyou”的根过程?
  • 并且最终子进程必须退出系统而不做任何事情?

      #include <iostream>
      #include <sys/types.h>
      #include <unistd.h>
      using namespace std;
    
      pid_t pid1,pid2,pid3,pid4;
      int function(){                        
      pid1=fork(); 
      if(pid1>0)
      {
      cout << "hi" << getpid()<<" " << getppid()<< endl; /*first child process should print "hi"*/
      }
      pid2=fork();
      cout << "hell" << getpid()<<" " << getppid()<< endl;
      pid3=fork();
      cout << "how "  <<getpid() <<" "<<getppid() <<endl;
      pid4=fork();
    
      if(pid4>0){
      return 0;/* final child process should exit from the system with out doing anything*/                                      
                }
            else{
     cout << "areyou "<<getpid()<<" "<<getppid()<<endl; 
                }
            }
    
     int main() {
    
     /* and the root process should print  "are you"*/
        function();
       }
    

    -with if(pid1&gt; 0)我想我试图实现第一个孩子输出“hi”,我觉得我迷失了解我怎么才能得到只有根父进程来打印“areyou”,以及如何控制最后一个孩子退出而不做任何事情

2 个答案:

答案 0 :(得分:0)

  

if(pid1&gt; 0)我猜我试图实现第一个孩子输出“hi”

不,它是获得正pid(成功时),因为它获取刚刚分叉的子进程的id,或者如果fork调用失败则为-1。孩子收到的返回值为0

你想做的事情是这样的:

if(pid1 < 0)
{
    cout << "fork failed to create a child process."
}
else if (pid1 > 0) // Parent
{
     cout << "areyou";
}
else // child
{
     cout << "hi";
}

答案 1 :(得分:0)

您可以执行类似

的操作
void function()
{                        
    pid_t pid1, pid2, pid3, pid4;
    pid1 = fork(); 
    if (pid1 == 0)
    {
        // first child process should print "hi"
        cout << "hi " << getpid() << " " << getppid()<< endl;

    }
    pid2 = fork();
    cout << "hell " << getpid() <<" " << getppid() << endl;
    pid3 = fork();
    cout << "how "  << getpid() <<" "<<getppid() << endl;
    pid4 = fork(); // Mostly useless as only parent print something for this one

    if (pid1 == 0 && pid2 == 0 && pid3 == 0 && pid4 == 0){
        return; // final child process should exit from the system with out doing anything
    } else if (pid1 > 0 && pid2 > 0 && pid3 > 0 && pid4 > 0){
        cout << "areyou "<< getpid() << "  "<< getppid() << endl;
    }
}

Demo