如何使子进程和父进程操作相同的全局变量?

问题描述

我有一个设置为false的布尔变量“ ab”,但是我想在子进程执行的函数中将其更改为true。我尝试使用管道,但没有确切地做什么以及如何做。有人可以帮我吗?

该代码创建2个子进程,并进入无限循环,并在3秒后使用alarm(3)向两个子进程发送信号。

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

void passage(int);
void AB(int);
void BA(int);

bool ab = true;

int pid[2];
int i = 1;

void
passage(int signum)
{
    printf("Voiture %d passée\n",i);
    i++;
    ab = !ab;
}

void
AB(int sig)
{

    if (ab == false) {
        printf("feu1: ROUGE | feu2: VERT\n");
        ab = true;
    }
}

void
BA(int sig)
{

    if (ab == true) {
        // ab = false;
        printf("feu1: VERT | feu2: ROUGE\n");
    }
}

int
main()
{

    struct sigaction action;

    action.sa_handler = passage;
    sigaction(SIGALRM,&action,NULL);

    pid[0] = fork();
    if (pid[0] != -1) {
        if (pid[0] == 0) {
            // Code du child 1
            printf("test1\n");
            signal(SIGUSR1,AB);
            while (1);

        }
        else {
            pid[1] = fork();
            if (pid[1] == 0) {
                // Code child 2
                printf("test2\n");
                signal(SIGUSR2,BA);
                while (1);

            }
            else {
                // parent precessus
                // send signals to the two childs after 3s
                printf("PONT OUVERT\n");

                for (;;) {
                    alarm(3);
                    pause();
                    kill(pid[0],SIGUSR1);
                    kill(pid[1],SIGUSR2);

                }
                // gcc test.c -o test
            }
        }
    }

    return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)