在我的代码如下,我正在运行一个父进程,它分叉成两个子进程。在之后(getpid());,两个孩子都退出状态。Wait()运行两次?
然而,当我运行父进程,它在某种程度上总是决定运行两次父节(设置了两个不同的PID值),我只是不能让它只运行一次。有一种方法可以在获得一个值后等待停止吗?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
void child(int n) { //n: child pid
printf("\nPID of child: %i \n", n);
//random number rand
int randFile = open("/dev/random", O_RDONLY);
int r;
if(rand < 0)
printf("ERROR: %s\n", strerror(errno));
else {
unsigned int seed;
read(randFile, &seed, 4); //&rand is a pointer, 4 bytes
int randClose = close(randFile);
srand(seed); //seeds rand() with random from /dev/random
r = rand();
if(randClose < 0)
printf("ERROR: %s\n", strerror(errno));
//range between 5 and 20 seconds
r = r % 20;
if(r < 5)
r = 5;
}
// printf("\n%i\n", r);
sleep(r);
// sleep(1);
printf("\n child with pid %i FINISHED\n", n);
exit(r);
}
int main() {
printf("\nPREFORK\n");
int parentPID = getpid();
int child0 = fork();
if(child0 < 0)
printf("ERROR: %s\n", strerror(errno));
int child1 = fork();
if(child1 < 0)
printf("\nERROR: %s\n", strerror(errno));
if(getpid() == parentPID)
printf("\nPOSTFORK\n");
//if children
if(child1 == 0) //using child1 as child-testing value b/c when child1 is set, both children are already forked
child(getpid());
int status;
int pid = wait(&status);
//parent
if(getpid() != 0) {
if(pid < 0)
printf("\nERROR: %s\n", strerror(errno));
if (pid > 0 && pid != parentPID) {
printf("\nPID of FINISHED CHILD: %i\n Asleep for %i seconds\n", pid, WEXITSTATUS(status));
printf("PARENT ENDED. PROGRAM TERMINATING");
}
}
return 0;
}
请出示在此之前的代码为好,你要求的代码叉成两个子进程。如果我们看到代码在做什么,而不是猜测发生了什么,并且猜测child1设置为什么,那么更容易。还要注意,getpid()永远不会是0.您的进程始终有一个非零进程ID。 – nos
完成。我没有意识到我们可以突出显示并点击方括号来批量添加代码。我其实只是在每一行上做了四个空格......谢谢。 – CodeSammich