本文整理汇总了C++中sem_close函数的典型用法代码示例。如果您正苦于以下问题:C++ sem_close函数的具体用法?C++ sem_close怎么用?C++ sem_close使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sem_close函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main() {
VolumeManager *vm;
CommandListener *cl;
NetlinkManager *nm;
SLOGI("Vold 2.1 (the revenge) firing up");
mkdir("/dev/block/vold", 0755);
udisk_sem=sem_open("vold_sem",1);
/* Create our singleton managers */
if (!(vm = VolumeManager::Instance())) {
SLOGE("Unable to create VolumeManager");
exit(1);
};
if (!(nm = NetlinkManager::Instance())) {
SLOGE("Unable to create NetlinkManager");
exit(1);
};
cl = new CommandListener();
vm->setBroadcaster((SocketListener *) cl);
nm->setBroadcaster((SocketListener *) cl);
if (vm->start()) {
SLOGE("Unable to start VolumeManager (%s)", strerror(errno));
exit(1);
}
if (process_config(vm)) {
SLOGE("Error reading configuration (%s)... continuing anyways", strerror(errno));
}
if (nm->start()) {
SLOGE("Unable to start NetlinkManager (%s)", strerror(errno));
exit(1);
}
coldboot("/sys/block");
// coldboot("/sys/class/switch");
/*
* Now that we're up, we can respond to commands
*/
if (cl->startListener()) {
SLOGE("Unable to start CommandListener (%s)", strerror(errno));
exit(1);
}
// Eventually we'll become the monitoring thread
while(1) {
sleep(1000);
}
sem_close(udisk_sem);
sem_unlink("vold_sem");
SLOGI("Vold exiting");
exit(0);
}
示例2: main
/* The main test function. */
int main(int argc, char *argv[])
{
int ret, status;
pid_t child, ctl;
sem_t *sem;
struct timespec tsini, tsfin;
/* Initialize output */
output_init();
/* read current time */
ret = clock_gettime(CLOCK_REALTIME, &tsini);
if (ret == -1)
UNRESOLVED(errno, "Unable to read CLOCK_REALTIME clock");
/* Set temporary value in tsfin for semaphore timeout */
tsfin.tv_sec = tsini.tv_sec + 3;
tsfin.tv_nsec = tsini.tv_nsec;
/* Create the child */
child = fork();
if (child == -1)
UNRESOLVED(errno, "Failed to fork");
/* Open the semaphore */
sem = sem_open(SEM_NAME, O_CREAT, O_RDWR, 0);
if (sem == SEM_FAILED)
UNRESOLVED(errno, "Failed to open the semaphore (try executing "
"as root)");
/* sleep 1 second */
sleep(1);
/* child posts the semaphore and terminates */
if (child == 0) {
do {
ret = sem_post(sem);
} while (ret == -1 && errno == EINTR);
if (ret == -1)
UNRESOLVED(errno, "Failed to post the semaphore");
ret = sem_close(sem);
if (ret == -1)
UNRESOLVED(errno, "Failed to close the semaphore");
/* The child stops here */
exit(0);
}
/* Parent waits for the semaphore */
do {
ret = sem_timedwait(sem, &tsfin);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
if (errno == ETIMEDOUT)
FAILED("The new process does not execute");
UNRESOLVED(errno, "Failed to wait for the semaphore");
}
/* We don't need the semaphore anymore */
ret = sem_close(sem);
if (ret == -1)
UNRESOLVED(errno, "Failed to close the semaphore");
ret = sem_unlink(SEM_NAME);
if (ret == -1)
UNRESOLVED(errno, "Unable to unlink the semaphore");
/* Parent joins the child */
ctl = waitpid(child, &status, 0);
if (ctl != child)
UNRESOLVED(errno, "Waitpid returned the wrong PID");
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
UNRESOLVED(status, "Child exited abnormally");
/* Check the global duration */
ret = clock_gettime(CLOCK_REALTIME, &tsfin);
if (ret == -1)
UNRESOLVED(errno, "Unable to read CLOCK_REALTIME clock");
if (tsfin.tv_nsec < tsini.tv_nsec)
tsfin.tv_sec -= 1;
status = tsfin.tv_sec - tsini.tv_sec;
if (status >= 2) {
/* the operation was more than 2 secs long */
FAILED("the processes did not execute concurrently");
}
output("Test passed\n");
PASSED;
}
示例3: sem_unlink
int sem_unlink(FAR const char *name)
{
FAR struct inode *inode;
FAR const char *relpath = NULL;
char fullpath[MAX_SEMPATH];
int errcode;
int ret;
/* Get the full path to the semaphore */
snprintf(fullpath, MAX_SEMPATH, CONFIG_FS_NAMED_SEMPATH "/%s", name);
/* Get the inode for this semaphore. */
sched_lock();
inode = inode_find(fullpath, &relpath);
if (!inode)
{
/* There is no inode that includes in this path */
errcode = ENOENT;
goto errout;
}
/* Verify that what we found is, indeed, a semaphore */
if (!INODE_IS_NAMEDSEM(inode))
{
errcode = ENXIO;
goto errout_with_inode;
}
/* Refuse to unlink the inode if it has children. I.e., if it is
* functioning as a directory and the directory is not empty.
*/
inode_semtake();
if (inode->i_child != NULL)
{
errcode = ENOTEMPTY;
goto errout_with_semaphore;
}
/* Remove the old inode from the tree. Because we hold a reference count
* on the inode, it will not be deleted now. This will set the
* FSNODEFLAG_DELETED bit in the inode flags.
*/
ret = inode_remove(fullpath);
/* inode_remove() should always fail with -EBUSY because we hae a reference
* on the inode. -EBUSY means taht the inode was, indeed, unlinked but
* thatis could not be freed because there are refrences.
*/
DEBUGASSERT(ret >= 0 || ret == -EBUSY);
UNUSED(ret);
/* Now we do not release the reference count in the normal way (by calling
* inode release. Rather, we call sem_close(). sem_close will decrement
* the reference count on the inode. But it will also free the semaphore
* if that reference count decrements to zero. Since we hold one reference,
* that can only occur if the semaphore is not in-use.
*/
inode_semgive();
ret = sem_close((FAR sem_t *)inode->u.i_nsem);
sched_unlock();
return ret;
errout_with_semaphore:
inode_semgive();
errout_with_inode:
inode_release(inode);
errout:
set_errno(errcode);
sched_unlock();
return ERROR;
}
示例4: create_server
void create_server(void)
{
int status;
int sd[MAX_PORT];
int addrlen;
const unsigned short int port[] = {0x9234, 0x9235, 0x9236, 0x9237};
struct sockaddr_in sin[MAX_PORT];
int fd1;
int j = 0;
int i = 0;
pid_t child_id[4];
// struct timeval timeout;
pid_t parent_id = getpid();
sem_t *mutex;
fd_set read_fd_set;
fd_set pipe_fd_set; /* pipe set */
int pd[MAX_PORT][2]; /* pipes */
char buf[MAX_PORT];
int count = 0;
fd1 = open ("/tmp/whatever.txt", O_CREAT | O_RDWR | O_TRUNC, 0644);
// timeout.tv_sec = 1 * 60;
// timeout.tv_usec = 0;
/* Initialize the set of active sockets. */
FD_ZERO (&read_fd_set);
FD_ZERO (&pipe_fd_set);
mutex = sem_open(SEM_NAME, O_CREAT, 0644, 1);
if(mutex == SEM_FAILED)
{
log_stuff("unable to create semaphore",errno);
sem_unlink(SEM_NAME);
exit(EXIT_FAILURE);
}
system("echo begin > /tmp/error.txt");
for(; j < MAX_PORT; j++) {
populate_sock(&sd[j],&sin[j], port[j]);
if(pipe(pd[j]) == -1) {
log_stuff(strerror(errno), __LINE__);
exit(EXIT_FAILURE);
}
// fcntl(sd[j], F_SETFL, O_NONBLOCK);
log_stuff("filedesc we get=", sd[j]);
FD_SET (sd[j], &read_fd_set);
FD_SET (pd[j][0], &pipe_fd_set); /* */
child_here(read_fd_set, fd1, mutex, pd[j][1]);/* */
}
if(getpid() == parent_id) {
parent_stuff(pipe_fd_set, fd1, mutex);
}
log_stuff("after waitpid line=", getpid());
close(fd1);
sem_close(mutex);
sem_unlink(SEM_NAME);
exit(EXIT_FAILURE);
}
示例5: main
/* The main test function. */
int main( int argc, char * argv[] )
{
int ret, i;
char * name = "/sem_open_15_1";
sem_t * sems[ 4 ];
/* Initialize output */
output_init();
/* Initialize all semaphores */
for ( i = 0; i < 4; i++ )
{
sems[ i ] = sem_open( name, O_CREAT, 0777, 1 );
if ( sems[ i ] == SEM_FAILED )
{
UNRESOLVED( errno, "Failed to sem_open" );
}
}
/* Check all calls returned the same @ */
for ( i = 0; i < 3; i++ )
{
if ( sems[ i ] != sems[ i + 1 ] )
{
FAILED( "sem_open returned a different address" );
}
/* Close some semaphores */
ret = sem_close( sems[ i ] );
if ( ret != 0 )
{
UNRESOLVED( errno, "Failed to sem_close" );
}
}
/* Now, reopen, we should still get the same address */
for ( i = 0; i < 3; i++ )
{
sems[ i ] = sem_open( name, O_CREAT, 0777, 1 );
if ( sems[ i ] == SEM_FAILED )
{
UNRESOLVED( errno, "Failed to sem_open" );
}
}
/* Check all calls returned the same @ */
for ( i = 0; i < 3; i++ )
{
if ( sems[ i ] != sems[ i + 1 ] )
{
FAILED( "sem_open returned a different address" );
}
}
/* Close all semaphores */
for ( i = 0; i < 4; i++ )
{
ret = sem_close( sems[ i ] );
if ( ret != 0 )
{
UNRESOLVED( errno, "Failed to sem_close" );
}
}
sem_unlink( name );
/* Test passed */
#if VERBOSE > 0
output( "Test passed\n" );
#endif
PASSED;
}
示例6: startServer
void startServer(int portnum){
struct sockaddr_in clientAddr; // client socket informations
socklen_t clientAddrLen; // client socket address length
// initialize size of struct
clientAddrLen = sizeof(struct sockaddr_in);
//clear junk values
memset(&clientAddr,0,clientAddrLen);
if((gI_socketFd = initializeSocket(portnum))==-1){
perror("Initialize socket");
return;
}
fprintf(stderr,"[%ld]MainServer initialized socket\n",(long)gPid_server);
// create a semafor to control writing sequential to pipe
sem_unlink(PIPE_CONTROL_SEM);
getnamed(PIPE_CONTROL_SEM,&gSemP_pipeSem,1);
pipe(gPipe_cwpr);
pipe(gPipe_crpw);
// TODO : check pipe errors
pthread_t th_pipeListener;
pthread_create(&th_pipeListener,NULL,listenPipe,NULL);
memset(&serverList,0,sizeof(hmlist_t)); //clear junks
gettimeofday(&endTime,NULL);
diffTime = getTimeDif(startTime,endTime);
printf("[%ld]MainServer is builded in %ld ms\n",(long)gPid_server,diffTime);
hmServData_t miniServer;
pid_t pidChild=-1;
pid_t pidClient=-1;
while(!doneflag){
printf("[%ld]MainServer waiting for clients...\n",(long)gPid_server);
// accept clients
fdClient = accept(gI_socketFd,(struct sockaddr*)&clientAddr,&clientAddrLen);
if(fdClient !=-1 && !doneflag){
// client send pid address and server creates new mini server to serv
read(fdClient,&pidClient,sizeof(pid_t));
if( (pidChild = fork())==-1){
perror("Fork");
doneflag=1;
}else if(pidChild==0){ // child here
break;
}else{ // parent here
// pair server-client informations
memset(&miniServer,0,sizeof(hmServData_t));
miniServer.pidServer=pidChild;
miniServer.pidClient=pidClient;
miniServer.fdSocket = fdClient;
addList(&serverList,&miniServer); // store child informations
gettimeofday(&endTime,NULL);
diffTime = getTimeDif(startTime,endTime);
printf("Client[%ld] connected to server[%ld] in %ld ms\n",
(long)pidClient,(long)pidChild,diffTime);
}
}else doneflag=1;
}
if(pidChild ==0){ // child here
// no need to re-open semafor because we forked all memory
/*sem_close(gSemP_pipeSem);
getnamed(PIPE_CONTROL_SEM,&gSemP_pipeSem,1);*/
gPid_server = getpid(); // assing new mini server pid
deleteList(&serverList); // remove parent values
startMiniServer(pidClient); // start server
pthread_join(th_pipeListener,NULL);
sem_close(gSemP_pipeSem);
close(gI_socketFd); // close spesific socket fildes
// return main and close mini server
}else{ // main server here
killAllChilds(SIGINT);
close(gPipe_cwpr[1]); //close pipe to kill thread
while(wait(NULL)!=-1){} // wait childs
// TODO : create thread to wait childs
deleteList(&serverList);
printf("[%ld]MainServer Waiting for threads\n",(long)gPid_server);
pthread_join(th_pipeListener,NULL);
sem_close(gSemP_pipeSem);
close(gI_socketFd);
}
}
示例7: close_sem
int close_sem(sem_t* handle)
{
return sem_close(handle);
}
示例8: puts
//.........这里部分代码省略.........
* E_POSIX_Semaphore_Create_support only fails if
* ENOSYS - When semaphore is shared between processes.
* ENOSPC - When out of memory.
*/
/*
* Validate we can wait on a semaphore opened with sem_open.
*/
puts( "Init: sem_wait on sem1" );
status = sem_wait(n_sem1);
fatal_posix_service_status( status, 0, "sem_wait opened semaphore");
/*
* Validate a second open returns the same semaphore.
*/
puts( "Init: sem_open - Open an existing sem ( same id )" );
n_sem2 = sem_open("sem1", 0 );
rtems_test_assert( n_sem2 == n_sem1 );
/*
* Unlink the semaphore, then verify an open of the same name produces a
* different semaphore.
*/
puts( "Init: sem_unlink - sem1 SUCCESSFUL" );
status = sem_unlink( "sem1" );
fatal_posix_service_status( status, 0, "sem_unlink locked semaphore");
puts( "Init: sem_open - Reopen sem1 SUCCESSFUL with a different id" );
n_sem2 = sem_open( "sem1", O_CREAT | O_EXCL, 0777, 1);
rtems_test_assert( n_sem2 != SEM_FAILED );
rtems_test_assert( n_sem2 != n_sem1 );
/*
* Validate we can call close on a semaphore opened with sem_open.
*/
puts( "Init: sem_close (1) - SUCCESSFUL" );
status = sem_close( n_sem1 );
fatal_posix_service_status( status, 0, "sem_close semaphore");
/*
* Validate it n_sem2 (the last open for sem1 name can be
* correctly closed and unlinked.
*/
puts( "Init: sem_close (2) - SUCCESSFUL" );
status = sem_close( n_sem2 );
fatal_posix_service_status( status, 0, "sem_close semaphore");
puts( "Init: sem_unlink - sem1 (2) SUCCESSFUL" );
status = sem_unlink( "sem1" );
fatal_posix_service_status( status, 0, "sem_unlink locked semaphore");
puts( "Init: sem_close - UNSUCCESSFUL (EINVAL)" );
status = sem_close(n_sem2);
fatal_posix_service_status( status, -1, "sem_close error return status");
fatal_posix_service_status( errno, EINVAL, "sem_close errno EINVAL");
puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" );
status = sem_unlink("sem1");
fatal_posix_service_status( status, -1, "sem_unlink error return status");
fatal_posix_service_status( errno, ENOENT, "sem_close errno EINVAL");
/*
* Validate we can unlink (2)
*/
puts( "Init: sem_unlink (NULL) - EINVAL" );
status = sem_unlink( NULL );
fatal_posix_service_status( status, -1, "sem_unlink error return status");
fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value");
puts( "Init: sem_unlink (\"\") - EINVAL" );
status = sem_unlink( "" );
fatal_posix_service_status( status, -1, "sem_unlink error return status");
fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value");
/*
* XXX - Cant' create location OBJECTS_ERROR or OBJECTS_REMOTE.
* sem_close and sem_unlink.
*/
puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" );
status = sem_unlink("sem2");
fatal_posix_service_status( status, -1, "sem_unlink error return status");
fatal_posix_service_status( errno, ENOENT, "sem_unlink errno ENOENT");
rtems_test_assert( (status == -1) && (errno == ENOENT) );
/* Try adding in unlinking before closing... (can we still open?) */
puts( "*** END OF POSIX SEMAPHORE MANAGER TEST 1 ***" );
rtems_test_exit(0);
return NULL; /* just so the compiler thinks we returned something */
}
示例9: main
int main(int argc, char** argv)
{
shm_unlink("SHARED_MEMORY_NAME");
sem_unlink("EMPTY_BUF_SEMAPHORE_NAME");
sem_unlink("FULL_BUF_SEMAPHORE_NAME");
sem_unlink("MUTEX_SEMAPHORE_NAME");
// Создаем разделяемую память для хранения данных
int shm_buf = shm_open("SHARED_MEMORY_NAME", O_CREAT | O_RDWR, 0777);
if(shm_buf == -1)
{
perror("shm_create");
return -1;
}
int ftr_buf = ftruncate(shm_buf, SHARED_MEMORY_SIZE);
if(ftr_buf == -1)
{
perror("truncate");
return -1;
}
// Общий размер буфера для записи
int size = SHARED_MEMORY_SIZE / sizeof(int);
// Создаем семафоры для исключения записи в переполненный буфер,
// для считывания из пустого буфера и для взаимоисключения
sem_t* empty_buf_sem = sem_open("EMPTY_BUF_SEMAPHORE_NAME", O_CREAT, 0777, size);
sem_t* full_buf_sem = sem_open("FULL_BUF_SEMAPHORE_NAME", O_CREAT, 0777, 0);
sem_t* mutex_sem = sem_open("MUTEX_SEMAPHORE_NAME", O_CREAT, 0777, 1);
close(shm_buf);
sem_close(empty_buf_sem);
sem_close(full_buf_sem);
sem_close(mutex_sem);
//-------------------------------------------------------------------------------------
int process = fork();
// Дочерний процесс (запись)
if(process == 0)
{
// Открываем семафоры
sem_t* empty_buf_sem = sem_open("EMPTY_BUF_SEMAPHORE_NAME", 0, 0777, size);
sem_t* full_buf_sem = sem_open("FULL_BUF_SEMAPHORE_NAME", 0, 0777, 0);
sem_t* mutex_sem = sem_open("MUTEX_SEMAPHORE_NAME", 0, 0777, 1);
// Открываем разделяемую память
int shm_buf = shm_open("SHARED_MEMORY_NAME", O_RDWR, 0777);
if(shm_buf == 1)
{
perror("shm_open");
return -1;
}
// Отображаем память
void* addr = mmap(0, SHARED_MEMORY_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED, shm_buf, 0);
//--------------------------------------------------------------------------------------
// Генерируем числа и записываем их в разделяемую память
int i = 0;
int number;
void* TempBuf = malloc(sizeof(int));
srand(time(NULL));
for(i = 0; i < size; ++i)
{
number = 1 + rand() % 100;
printf("write: %d\n", number);
sem_wait(empty_buf_sem);
sem_wait(mutex_sem);
sprintf(TempBuf, "%d", number);
memcpy( (int*)addr + i, (int*)TempBuf, sizeof(int) );
sem_post(mutex_sem);
sem_post(full_buf_sem);
}
printf("Finish writing\n");
//--------------------------------------------------------------------------------------
// Снимаем отображение
munmap(addr, SHARED_MEMORY_SIZE);
// Закрываем семафоры
sem_close(empty_buf_sem);
sem_close(full_buf_sem);
sem_close(mutex_sem);
return 0;
}
//.........这里部分代码省略.........
示例10: main
int main(int argc, char** argv)
{
int optchar;
pthread_t threadid;
char semaphore_name[32];
while ((optchar = getopt(argc, argv, "dmp")) != EOF)
{
switch (optchar)
{
case 'd':
s_debug = 1;
break;
case 'm':
s_do_mutual_exclusion = 1;
break;
case 'p':
s_do_printf = 1;
break;
default:
assert(0);
}
}
/*
* Use the ipcs and ipcrm commands to clean up named semaphores left by
* aborted instances of this process.
*/
snprintf(semaphore_name, sizeof(semaphore_name), "/drd-sem-open-test-%d",
getpid());
s_sem = sem_open(semaphore_name, O_CREAT | O_EXCL, 0600, 1);
if (s_sem == SEM_FAILED)
{
fprintf(stderr, "Failed to create a semaphore with name %s\n",
semaphore_name);
exit(1);
}
/*
* Switch to line-buffered mode, such that timing information can be
* obtained for each printf() call with strace.
*/
setlinebuf(stdout);
if (s_debug)
{
printf("&s_d1 = %p; &s_d2 = %p; &s_d3 = %p\n", &s_d1, &s_d2, &s_d3);
}
s_d1 = 1;
s_d3 = 3;
pthread_create(&threadid, 0, thread_func, 0);
sleep(1); /* Wait until thread_func() finished. */
{
if (s_do_mutual_exclusion) sem_wait(s_sem);
s_d3++;
if (s_do_mutual_exclusion) sem_post(s_sem);
}
/* Wait until the thread finished. */
pthread_join(threadid, 0);
if (s_do_printf) printf("s_d2 = %g (should be 2)\n", s_d2);
if (s_do_printf) printf("s_d3 = %g (should be 5)\n", s_d3);
sem_close(s_sem);
sem_unlink(semaphore_name);
return 0;
}
示例11: std_close_proc_sem
extern int std_close_proc_sem(std_proc_sem_id_t semId)
{
return sem_close((sem_t *) semId) == 0;
}
示例12: dinit_filters
void dinit_filters(struct liveStream *ctx)
{
avfilter_graph_free(&ctx->filter_graph);
sem_close(&ctx->filter_lock);
}
示例13: main
int main(int argc, char **args) {
if (argc != 4) {
printf("Not a suitable number of program parameters\n");
return (1);
}
/************************************
Utworz semafor posixowy. Ustaw jego wartosc na 1
*************************************/
sem_t *sem_id = sem_open(SEM_NAME, O_CREAT, 0600, 1);
int fd = open(FILE_NAME, O_WRONLY | O_CREAT , 0644);
int parentLoopCounter = atoi(args[1]);
int childLoopCounter = atoi(args[2]);
char buf[50];
pid_t childPid;
int max_sleep_time = atoi(args[3]);
if ((childPid = fork())) {
int status = 0;
srand((unsigned) time(0));
while (parentLoopCounter--) {
int s = rand() % max_sleep_time + 1;
sleep(s);
/**************q****************************
Sekcja krytyczna. Zabezpiecz dostep semaforem
******************************************/
sem_wait(sem_id);
sprintf(buf, "Wpis rodzica. Petla %d. Spalem %d\n", parentLoopCounter, s);
write(fd, buf, strlen(buf));
write(1, buf, strlen(buf));
/****************************************************
Koniec sekcji krytycznej
****************************************************/
sem_post(sem_id);
}
waitpid(childPid, &status, 0);
} else {
srand((unsigned) time(0));
while (childLoopCounter--) {
int s = rand() % max_sleep_time + 1;
sleep(s);
/******************************************
Sekcja krytyczna. Zabezpiecz dostep semaforem
******************************************/
sem_wait(sem_id);
sprintf(buf, "Wpis dziecka. Petla %d. Spalem %d\n", childLoopCounter, s);
write(fd, buf, strlen(buf));
write(1, buf, strlen(buf));
/****************************************************
Koniec sekcji krytycznej
****************************************************/
sem_post(sem_id);
}
_exit(0);
}
/***************************************
Posprzataj semafor
***************************************/
sem_close(sem_id);
sem_unlink(SEM_NAME);
close(fd);
return 0;
}
示例14: sem_close
bool CameraStatus::uinitSemaphore(void)
{
sem_close(this->statusMutex);
sem_unlink("CCDSTATUS");
return true;
}
示例15: startMiniServer
void startMiniServer(pid_t pidClient){
Command_e command=DIE;
DIR *pDir=NULL;
char strSemNameFifo[MAX_FILE_NAME];
pthread_t th_fifoController;
pDir = opendir(LOCAL_DIR);
if(pDir==NULL){
perror("Dir open error :");
return;
}
memset(strSemNameFifo,0,MAX_FILE_NAME);
sprintf(strSemNameFifo,"/%ld.smf",(long)gPid_server);
getnamed(strSemNameFifo,&gSemP_fifoSem,1);
pthread_create(&th_fifoController,NULL,fifoController,NULL);
pthread_mutex_init(&gMutex_lockSocket,NULL); // initialize mutex
write(fdClient,&gPid_server,sizeof(pid_t)); //send pid address to client
while(!doneflag){
read(fdClient,&command,sizeof(Command_e));
gettimeofday(&endTime,NULL);
diffTime = getTimeDif(startTime,endTime);
if(!doneflag){
if(command==LS_CLIENT){
printf("[%ld]MiniServer read LS_CLIENT command from [%ld]Client at %ld ms\n",
(long)gPid_server,(long)pidClient,diffTime);
lsClient(fdClient,pidClient);
}else if(command==LIST_SERVER){
//lock mutex and write filenames to socket
printf("[%ld]MiniServer read LIST_SERVER command from [%ld]Client at %ld ms\n",
(long)gPid_server,(long)pidClient,diffTime);
pthread_mutex_lock(&gMutex_lockSocket);
listLocalFiles(pDir,fdClient);
pthread_mutex_unlock(&gMutex_lockSocket);
}else if(command ==DIE){
printf("[%ld]MiniServer read DIE command from [%ld]Client at %ld ms\n",
(long)gPid_server,(long)pidClient,diffTime);
write(fdClient,&command,sizeof(Command_e));
doneflag=1;
// TODO: CHANGE DONEFLAG WITH SOMETHING DIFF
}else if(command == SEND_FILE){
sendFile(pidClient);
}
}
}
char fifoName[MAX_FILE_NAME];
memset(fifoName,0,MAX_FILE_NAME);
sprintf(fifoName,".%ld.ff",(long)gPid_server);
int fd = open(fifoName,O_RDWR);
pid_t killpid=0;
write(fd,&killpid,sizeof(pid_t));
close(fd);
pthread_mutex_destroy(&gMutex_lockSocket);
pthread_join(th_fifoController,NULL);
closedir(pDir);
sem_close(gSemP_fifoSem);
pDir=NULL; // handle dangling pointers
}