需要帮助使用fork()函数
问题描述:
- 在下面的节目我试图实现这些条件的实现有条件输出:
- 我想实现的是第一子进程打印“喜”?
- 和打印“areyou”的根进程?
-
和最终的子进程必须退出系统而不做任何事情?需要帮助使用fork()函数
#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如果(PID1> 0)我想我试图执行的第一个孩子输出“喜”,我觉得我理解失去了我怎样才能得到只有root父进程打印“areyou ”,以及如何控制的最后一个孩子出去做什么
答
你可以做这样的事情
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;
}
}
答
与IF(PID1> 0)我想我试图执行的第一个孩子,以输出退出‘喜’
不,这是父获得正向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
感谢澄清差异和如何区分使用返回类型的父进程和子进程,这将帮助我很多 – Swathi
多少进程你希望有?我计算'16' ...你可能需要更多'else'来区分孩子和父母。 – Jarod42
@Jardo是的只有使用16过程应该罚款我不想区分孩子和父母,但我想第一个孩子打印嗨和程序的根父进程打印“areyou” – Swathi