c - 使过程像二叉树一样,让每个 child 做不同的事情

标签 c linux

我正在执行以下程序,我在其中创建各种进程,就像它们是二叉树一样,我希望“左边”的 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/

相关文章:

c - C 中的 TCP/IP 简单文件服务器在 C 中读取服务器上的问题

c++ - 使用 termios api (c++) 在 Linux 中检测字符设备是否已断开连接

linux - 查找命令表达式错误

linux - VI 如何替换每行前n个字符后出现的n个字符

c - linux C 字符串转int

linux - 使用shell脚本删除前10个最大的常规文件

c++ - 尝试使用外部库时 undefined reference

c - 当隐式规则没有说明可执行文件时,make 如何从 C 源文件构建可执行文件?

c - Linux内核有main函数吗?

不使用标准库的十六进制 C 代码