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

C 如何使子进程和父进程操作相同的全局变量?,c,linux,signals,ipc,C,Linux,Signals,Ipc,我有一个布尔变量“ab”,它被设置为false,但我想在子进程执行的函数中将它更改为true。我试着用管道,但我不知道该怎么做,怎么做。有人能帮我吗 代码创建2个子进程,并使用报警(3)进入无限循环,在3s后向两个子进程发送信号 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 无效通道(int); 无效AB(int); 文学士(内部); 布尔ab=真; int-pid[2]; int i=1; 无效的 通道(内部标志) { printf(“通过%d次”,i); i++; ab=!

我有一个布尔变量“ab”,它被设置为false,但我想在子进程执行的函数中将它更改为true。我试着用管道,但我不知道该怎么做,怎么做。有人能帮我吗

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

#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
无效通道(int);
无效AB(int);
文学士(内部);
布尔ab=真;
int-pid[2];
int i=1;
无效的
通道(内部标志)
{
printf(“通过%d次”,i);
i++;
ab=!ab;
}
无效的
AB(内部信号)
{
如果(ab==false){
printf(“feu1:ROUGE | feu2:VERT\n”);
ab=真;
}
}
无效的
文学士(内部信号)
{
如果(ab==true){
//ab=假;
printf(“feu1:VERT | feu2:ROUGE\n”);
}
}
int
main()
{
结构动作;
action.sa_handler=通道;
sigaction(SIGALRM,&action,NULL);
pid[0]=fork();
如果(pid[0]!=-1){
如果(pid[0]==0){
//代码du child 1
printf(“test1\n”);
信号(SIGUSR1,AB);
而(1),;
}
否则{
pid[1]=fork();
如果(pid[1]==0){
//代码儿童2
printf(“test2\n”);
信号(SIGUSR2,BA);
而(1),;
}
否则{
//父前体
//3秒钟后给两个孩子发信号
printf(“PONT OUVERT\n”);
对于(;;){
警报(3);
暂停();
kill(pid[0],SIGUSR1);
压井(pid[1],SIGUSR2);
}
//gcc测试.c-o测试
}
}
}
返回0;
}

您需要使用共享内存,请查看
shmemXXX
函数。是否要发送[无限]信号?或者,这是问题的一部分吗?要在父级和子级之间共享内存,请在父级[before
fork
]中,使用
shmget
等[SysV IPC]。更好的解决方案可能是使用信号量。您可以使用线程而不是进程。然后全局内存空间将在所有线程之间共享(参见pthread_create()。
#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;
}