我正在执行以下程序,我在其中创建各种进程,就像它们是二叉树一样,我希望“左边”的 child 做与“右边”的 child 不同的事情,但它输出了我 2 个 child 在右边或左边有 2 个 child ,我不想要那样。
void slice(int dir){
if (dir == 1) {
printf("izq ");
printf("child pid %d parent pid %d\n",getpid(),getppid());fflush(stdout);
}
else if (dir == 2){
printf("der ");
printf("child pid %d parent pid %d\n",getpid(),getppid());fflush(stdout);
}
}
void vector(int vector[], int length, int niveles){
for(int i=1;i<=niveles;i++)
{
int error = 0;
pid_t child_pid[2] = { -1, -1 };
for (int dir=0; dir<=1; ++dir) {
child_pid[dir] = fork();
if (child_pid[dir] == -1) {
error = 1;
perror("fork");
}
if (child_pid[dir] == 0) {
// Here is where you place the code the child should execute.
slice(dir);
exit(0);
}
}
for (int dir=0; dir<=1; ++dir) {
if (child_pid[dir] == -1)
continue;
int status;
pid_t pid = waitpid(child_pid[dir], &status, 0);
if (pid == -1) {
error = 1;
perror("waitpid");
}
else if (WIFSIGNALED(status)) {
error = 1;
fprintf(stderr, "Child was killed by signal %d\n", WTERMSIG(status));
}
else if (WEXITSTATUS(status) != 0) {
error = 1;
fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(status));
}
}
if (error)
exit(1);
}
}
我的目标是为“izq”调用一个函数,它做与“der”不同的事情,同时保持整个二叉树的想法。
最佳答案
请记住,父级和子级都从 fork
继续执行,因此您需要如下内容:
int error = 0;
pit_t child_pid[2] = { -1, -1 };
for (int dir=0; dir<=1; ++dir) {
child_pid[dir] = fork();
if (child_pid[dir] == -1) {
error = 1;
perror("fork");
}
if (child_pid[dir] == 0) {
// Here is where you place the code the child should execute.
exit(0);
}
}
for (int dir=0; dir<=1; ++dir) {
if (child_pid[dir] == -1)
continue;
int status;
pid_t pid = waitpid(child_pid[dir], &status, 0);
if (pid == -1) {
error = 1;
perror("waitpid");
}
else if (WIFSIGNALED(status)) {
error = 1;
fprintf(stderr, "Child was killed by signal %d\n", WTERMSIG(wstatus));
}
else if (WEXITSTATUS(status) != 0) {
error = 1;
fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(wstatus));
}
}
if (error)
exit(1);
关于c - 使过程像二叉树一样,让每个 child 做不同的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388450/