0

We have NUM_PLAYERS of child processes, and each of them outputs its id like

player 5: I scored 0 (PID = 411160)

but the problem is, all of them writing out simultaneously so it gets total mess of outputs.

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)

How can i make them wait for each other and write? Here is my actual code

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;
}
Burak Özmen
  • 865
  • 2
  • 11
  • 28

3 Answers3

0

You need to have some explicit locking mechanism. Alternatives include (but not limited) to lock file, or shared mutex.

For lock file: idea to use OS file locking semantics

Link: File locks for linux

For shared mutex: idea is to use shared memory and place process shared mutex into it.

Link: fork without exec, and pthread_mutex_t used by shared object

Link: Semaphores and shared memory

Community
  • 1
  • 1
Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18
0

You could use flock() on the output stream.

Use it like this:

int fd = ... /* Use open or fileno() here. */

flock(fd, LOCK_SH); 

/* Write to fd here. */

flock(fd, LOCK_UN);
alk
  • 69,737
  • 10
  • 105
  • 255
0

You may prevent simultaneous printf invocation by putting the function inside critical section. This section can be implemented by either shared mutex provided by the pthread library, or by named semaphores, or by unnamed semaphores. If you are going to protect your code by named semaphores (the easiest way), read more about sem_open, sem_post, sem_wait functions and sem_overview Linux manual pages.

MichaelGoren
  • 961
  • 9
  • 15