我们有NUM_PLAYERS个子进程,每个子进程都输出其ID,例如

player 5: I scored 0 (PID = 411160)


但是问题是,所有这些人都同时写出,因此完全混乱了输出。

player player player 1: I'm in this game (PID = 11049)
player 01: I scored 3: I'm in this game (PID = 11051: I'm in this game (PID = 1048)


我该如何让他们互相等待并写作?这是我的实际代码

int main(int argc, char *argv[])
{

    for (i = 0; i < NUM_PLAYERS; i++) {
        /* TODO: spawn the processes that simulate the players */
        switch(pid = fork()) {

        case -1:
            printf("Perror\n");
            exit(EXIT_FAILURE);
            break;
        case 0:
            //printf("%s<%d>%s<%d>\n", "CHILD ", getpid(), " ppid: ", getppid());
            //sleep(1);

            dup2(seedArray[i][0], STDIN_FILENO);
            close(seedArray[i][0]);

            dup2(scoreArray[i][1], STDOUT_FILENO);
            close(scoreArray[i][1]);

            sprintf(arg1,"%d",i);

            execv("./shooter", args);

            //shooter(i, seedArray[i][0], scoreArray[i][1]);
            //exit(EXIT_SUCCESS);
            break;
        default:
            //pid = wait(NULL);
            pidArray[i] = pid;
        }
    }


// SOME IRRELEVANT CODE HERE


    int status;
    for(i = 0;i < NUM_PLAYERS; i++)
    {
        wait(&status);
    }

    return 0;
}

最佳答案

您需要具有一些显式的锁定机制。替代方法包括(但不限于)锁定文件或共享互斥锁。

对于锁定文件:使用OS文件锁定语义的想法

链接:File locks for linux

对于共享互斥锁:想法是使用共享内存并将进程共享互斥锁放入其中。

链接:fork without exec, and pthread_mutex_t used by shared object

链接:Semaphores and shared memory

关于c - 同时写出不同的过程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21879177/

10-10 14:38