Skip to content

Instantly share code, notes, and snippets.

@mosfet1kg
Created July 2, 2015 12:10
Show Gist options
  • Select an option

  • Save mosfet1kg/d4f742fd1e4217b4f0ed to your computer and use it in GitHub Desktop.

Select an option

Save mosfet1kg/d4f742fd1e4217b4f0ed to your computer and use it in GitHub Desktop.
semaphore
#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>
//gcc -o main main.c -lpthread
int main(int argc, char **argv)
{
int fd, i,count=0,nloop=10,zero=0,*ptr;
sem_t mutex;
//파일을 열고 메모리와 매핑한다.
fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
write(fd,&zero,sizeof(int));
ptr = mmap(NULL,sizeof(int),PROT_READ |PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
/* 세마포어를 생성화고 초기화 한다. */
if( sem_init(&mutex,1,1) < 0)
{
perror("semaphore initilization");
exit(0);
}
if (fork() == 0) { /* child process*/
for (i = 0; i < nloop; i++) {
sem_wait(&mutex);
printf("child: %dn", (*ptr)++);
sem_post(&mutex);
}
exit(0);
}
/* 부모 프로세스로 돌아간다. */
for (i = 0; i < nloop; i++) {
sem_wait(&mutex);
printf("parent: %dn", (*ptr)++);
sem_post(&mutex);
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment