So I am having this issue with a Process Synchronization program in C.
I am supposed to make a code that, using fork()
, will produce something like this:
PARENT
PARENT
CHILD
PARENT
CHILD
PARENT
Using a code I found here, I was able to make it work but for some reasons, the first result that comes to screen is messed while all the others work just fine.
To compile, type : gcc test.c display.c -o test -pthread
Anyway, here is the code I am testing (I repeat: it's not my code):
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(void)
{
int i;
/* place semaphore in shared memory */
sem_t *sema = mmap(NULL, sizeof(sema), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0);
/* create/initialize semaphore */
if ( sem_init(sema, 1, 0) < 0)
{
perror("sem_init");
exit(EXIT_FAILURE);
}
int nloop=10;
int pid = fork();
if (pid == 0)
{
for (i = 0; i < nloop; i++)
{
// child unlocks semaphore
display("CHILD\n");
if (sem_post(sema) < 0)
perror("sem_post");
sleep(1);
}
if (munmap(sema, sizeof(sema)) < 0)
{
perror("munmap");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
else
{
for (i = 0; i < nloop; i++)
{ // parent starts waiting
display("PARENT\n");
if (sem_wait(sema) < 0)
perror("sem_wait");
// parent finished waiting
}
if (sem_destroy(sema) < 0)
{
perror("sem_destroy failed");
exit(EXIT_FAILURE);
}
if (munmap(sema, sizeof(sema)) < 0)
{
perror("munmap failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
}
Here is the output:
PACREHNT
ILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
PARENT
CHILD
Why does this happen in the beginning?