C 使用fork()获取子对象的子对象
我在操作系统课上遇到了一些问题。我需要用C编写一个函数,其中每个子函数生成另一个子函数,每个父函数只能有一个子函数。我还要打印他们的pid 这就是我到目前为止所做的:C 使用fork()获取子对象的子对象,c,operating-system,fork,system-calls,C,Operating System,Fork,System Calls,我在操作系统课上遇到了一些问题。我需要用C编写一个函数,其中每个子函数生成另一个子函数,每个父函数只能有一个子函数。我还要打印他们的pid 这就是我到目前为止所做的: #define MAX_COUNT 10 pid_t ex5_1 (pid_t pid) { pid = fork(); if (!pid) { printf("ID %d Parent %d \n", getpid(), getppid()); _exit(1);
#define MAX_COUNT 10
pid_t ex5_1 (pid_t pid) {
pid = fork();
if (!pid) {
printf("ID %d Parent %d \n", getpid(), getppid());
_exit(1);
}
return pid;
}
void ex5 () {
pid_t pid;
int i;
pid = fork();
for (i = 1; i <= MAX_COUNT; i++) {
pid = ex5_1(pid);
int status;
wait(&status);
}
}
#定义最大计数10
pid_t ex5_1(pid_t pid){
pid=fork();
如果(!pid){
printf(“ID%d父项%d\n”,getpid(),getppid());
_出口(1);
}
返回pid;
}
无效ex5(){
pid_t pid;
int i;
pid=fork();
对于(i=1;i以下是该男子对fork的看法:
成功时,在父进程中返回子进程的PID,在子进程中返回0。失败时,在父进程中返回-1,不创建子进程,并正确设置errno
所以你只需要像这样检查叉子的返回:
int pid = fork();
if (pid < 0)
// error handling here
else if (pid == 0)
// here you are in the child
else
// here you are in the parent
void child(int i)
{
int pid;
printf("Child number %d, ID %d Parent %d \n", i, getpid(), getppid());
if (i == MAX)
return;
pid = fork();
if (pid < 0)
// error handling here
else if (pid == 0)
child(++i);
else
waitpid(pid, null, 0);
exit(0);
}
int main() {
int i = 0;
int pid = fork();
if (pid < 0)
// error handling here
else if (pid == 0)
child(++i);
else
waitpid(pid, null, 0);
}
intpid=fork();
if(pid<0)
//这里的错误处理
否则如果(pid==0)
//这是你的孩子
其他的
//这是你的父母
最后,要在子对象中创建子对象,可以执行以下操作:
int pid = fork();
if (pid < 0)
// error handling here
else if (pid == 0)
// here you are in the child
else
// here you are in the parent
void child(int i)
{
int pid;
printf("Child number %d, ID %d Parent %d \n", i, getpid(), getppid());
if (i == MAX)
return;
pid = fork();
if (pid < 0)
// error handling here
else if (pid == 0)
child(++i);
else
waitpid(pid, null, 0);
exit(0);
}
int main() {
int i = 0;
int pid = fork();
if (pid < 0)
// error handling here
else if (pid == 0)
child(++i);
else
waitpid(pid, null, 0);
}
void子项(int i)
{
int-pid;
printf(“子编号%d,ID%d父项%d\n”,i,getpid(),getppid());
如果(i==最大值)
返回;
pid=fork();
if(pid<0)
//这里的错误处理
否则如果(pid==0)
儿童(++i);
其他的
waitpid(pid,null,0);
出口(0);
}
int main(){
int i=0;
int-pid=fork();
if(pid<0)
//这里的错误处理
否则如果(pid==0)
儿童(++i);
其他的
waitpid(pid,null,0);
}
你的问题是什么?Idk如何生成childBuy“specific number”的子对象的特定数量?你是说一个吗?想象X有一个子对象Y,而这个Y有一个子对象Z,一直到某个特定的number@EugeneSh.我想他想要一个进程链MAX_COUNT
deep。为什么不直接做intmain(void){child(0);}
?也是fork()
返回pid\u t
notint
@alk就为了printf的东西,他只想在子进程中打印,而不是在主进程中。我想他在这样分解时会理解得更好。@alk pid\u t数据类型是一个有符号的整数类型,能够表示进程ID。在GNU C库中,这是一个int。@mickeelb。非常感谢!现在我明白方法了!:-)