0

我在 C 中创建一个父子进程,这些进程使用字符数组作为共享内存,我希望执行按此顺序进行

父->子->父->子->父->子

....等等,我Wait(NULL)在父母中使用,但执行顺序是

父->子->父->父->父....

我试图在没有信号量或其他任何东西的情况下做到这一点我仍然是一个新手 Linux 程序员

int main(void)
{
    if (fork( ) == 0)
    { //child
        if( (id = shmget(key, sizeof(char[n]), 0)) == -1 )
        {
            exit(1);
        }
        shm = shmat(id, 0, 0);
        if (shm == (char *) -1)
            exit(2);
        .......................//some work
        ..........................
    }
    else //parent
    {
            if( (id = shmget(key, sizeof(char[n]), 0666 | IPC_CREAT)) == -1 )
            {
                exit(1);
            }
            shm = shmat(id, 0, 0); //attach shared memory to pointer
            if (shm == (char *) -1)
                exit(2); //error while atatching
                        ....
                        .....
        do
        {
            //parent turn here
            wait(NULL);
                        ....................................
                        //some work ..................
        }
        while(done!=1);
        shmdt(NULL);
        if( shmctl(id, IPC_RMID, NULL) == -1 )//delete the shared memory
        {
            perror("shmctl");
            exit(-1);
        }
    }
    exit(0);
}
4

1 回答 1

1
  1. 您可能想在调用 fork() 之前调用 shmget(IPC_CREAT),因为 POSIX 不保证调用后的执行顺序,因此子进程中的 shmget() 可能会失败,因为父进程没有机会创建共享段。

  2. wait() 等待子进程结束。它不用于在父进程和子进程之间进行调度。

  3. 你到底想做什么?

于 2013-02-19T22:44:20.613 回答