使用fork()的子进程和父进程 [英] Child and Parent process with fork()

查看:207
本文介绍了使用fork()的子进程和父进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,我需要一个程序,使9个子进程,之后,我必须倒计时3秒,使这9个进程,等待父亲的信号,他们收到这个信号,每个孩子应该说他是什么孩子(如果他是孩子#1,#2,#3等等,按他们的顺序)。

I'm having problems, I need to make a program that make 9 child processes, after that I have to put a countdown of 3 seconds and make these 9 processes to wait for a signal from the father, after they receive this signal, every children should say what children he is (if he is the children #1, #2, #3, etc..., in order in which they were made).

我所做的是在这里,一切都好,我认为,直到我作为孩子说的部分,我的号码是什么,我没有线索如何做,因为每个孩子是一个不同的过程,他们不共享内存和信号不能使用参数,现在我打印PID的功能称为处理程序,但如何打印我的号码,作为一个孩子?。

What I've done is here, everything is OK, I think, until the part where I have to say as a children, what is my number, I don't have a clue how to do it, because each children is a different process, they don't share memory and the signal can't use arguments for that, by now I'm printing the PID on the function called "handler", but how can I print my number, as a Children?.

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>

void handler(int x);

int main() {    
    pid_t child[9];
    pid_t child_pid;

    for (int i = 0; i < 9; ++i) {
        child_pid = fork();
        child[i] = child_pid;

        if (child_pid == 0)
            break;

        if (child_pid < 0) {
            perror("fork()");
            exit(EXIT_FAILURE);
        }
    }

    if (child_pid == 0) {
        signal(SIGUSR1, handler);
        pause();
    } else {
        printf("Countdown:\n");
        sleep(1);
        printf("3\n");
        sleep(1);
        printf("2\n");
        sleep(1);
        printf("1\n");
        sleep(1);

        for (int i = 0; i < 9; i++)
            kill(child[i], SIGUSR1); 

        waitpid(-1, NULL, 0);
    }

    return 0;
}

void handler(int sig) {
    printf("This is Child #%d\n", getpid());

    exit(0);
}


推荐答案

创建一个全局变量: / p>

Create a global variable:

int my_number;

然后在创建子代的循环中,执行:

Then in your loop that creates the children, do:

    if (child_pid == 0) {
        my_number = i;
        break;
    }

然后你可以在处理程序中使用这个变量:

Then you can use the variable in the handler:

void handler(int sig) {
    printf("This is Child #%d\n", my_number);

    exit(0);
}

这篇关于使用fork()的子进程和父进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆