コード例 #1
0
ファイル: buffer.c プロジェクト: aadhia/OperatingSystems
//This method instantiates an already allocated buffer.
void createBuffer(buffer **b, int size){
	//Allocates spaces
	(*b) = (buffer *)malloc(sizeof(buffer));
	//Instantiates pointers to 0, and stores size
	(*b)->nextIn = 0;
	(*b)->nextOut = 0;
	(*b)->length = size;
	//Allocates space for the char array
	(*b)->word = (char *)malloc(sizeof(char)*size);
	//Checks if it was able to allocate mem
	if(((*b)->word) == NULL){
		printf("Could not allocate memory for word\n");
		exit(EXIT_FAILURE);
	}
	//Allocates mem for semaphores
	semaphore *fullBuffers = (semaphore*)malloc(sizeof(semaphore)); 
	semaphore *emptyBuffers= (semaphore*)malloc(sizeof(semaphore)); 
	//Checks if allocated correctly
	if(fullBuffers == NULL || emptyBuffers == NULL){
		printf("Could not allocate memory for buffers\n");
		exit(EXIT_FAILURE);
	}
	//Creates the semaphores
	createSem(fullBuffers, 0);
	createSem(emptyBuffers, size);
	//Stores the semaphores in the buffer
	(*b)->full = &(*fullBuffers);
	(*b)->empty = &(*emptyBuffers);
}
コード例 #2
0
void PosixThreadSupport::startThreads(ThreadConstructionInfo& threadConstructionInfo)
{
        printf("%s creating %i threads.\n", __FUNCTION__, threadConstructionInfo.m_numThreads);
	m_activeSpuStatus.resize(threadConstructionInfo.m_numThreads);
        
	mainSemaphore = createSem("main");                
	//checkPThreadFunction(sem_wait(mainSemaphore));
   
	for (int i=0;i < threadConstructionInfo.m_numThreads;i++)
	{
		printf("starting thread %d\n",i);

		btSpuStatus&	spuStatus = m_activeSpuStatus[i];

		spuStatus.startSemaphore = createSem("threadLocal");                
                
                checkPThreadFunction(pthread_create(&spuStatus.thread, NULL, &threadFunction, (void*)&spuStatus));

		spuStatus.m_userPtr=0;

		spuStatus.m_taskId = i;
		spuStatus.m_commandId = 0;
		spuStatus.m_status = 0;
		spuStatus.m_lsMemory = threadConstructionInfo.m_lsMemoryFunc();
		spuStatus.m_userThreadFunc = threadConstructionInfo.m_userThreadFunc;
        spuStatus.threadUsed = 0;

		printf("started thread %d \n",i);
		
	}

}
コード例 #3
0
void createBuffer(buffer* b, buffer* nextBuffer){
	(b->nextOut) = 0;
	(b->nextIn) = 0;
	createSem(&(b->emptyBuffers), 1);
	createSem(&(b->fullBuffers), 0);
	//I'm onlly mallocing enough for a pointer, so it's not that terrible. 
	(b->nextBuffer) = malloc(sizeof(buffer*));
	(b->nextBuffer) = nextBuffer;
}
コード例 #4
0
ファイル: HW3.c プロジェクト: jsreese92/operating_Systems
main(){
  //initialize the ST library runtime, necessary for up() and down()
  st_init();

  /*
  BoundedBuffer readInput;
  createBuffer(&readInput, MAX_BUFF_SIZE);
  */

  int theBufferSize = MAX_BUFF_SIZE;
  semaphore fullSem;
  createSem(&fullSem, 0); //0 full buffers
  semaphore emptySem;
  createSem(&emptySem, MAX_BUFF_SIZE); //n empty buffers
  char theBuffer[MAX_BUFF_SIZE];

  BoundedBuffer theBoundedBuffer = {
    &theBufferSize,
    &fullSem,
    &emptySem,
    theBuffer
  };

  //have to derefernce the bufferSize pointer
  printf("Buffer Size: %d\n", (*theBoundedBuffer.bufferSize));

  int i;
  for(i = 0; i < 10; i++){
    up(theBoundedBuffer.fullBuffers);
  }
    for(i = 0; i < 6; i++){
      down(theBoundedBuffer.emptyBuffers);
  } 






  /*
  int i;
  for(i = 0; i < MAX_BUFF_SIZE; i++){
    up(&readInput.emptyBuffers);
    emptyBuffersVal++;
  }

  for (i = 0; i < MAX_BUFF_SIZE; i++){
    down(&readInput.emptyBuffers);
    emptyBuffersVal--;
  }
  */


  //buffDeposit(&readInput);
  //buffRemove(&readInput);
}
コード例 #5
0
ファイル: buffer.c プロジェクト: jsreese92/operating_Systems
void createBuffer(BoundedBuffer *b,  int theBuffSize){
  b->bufferSize = &theBuffSize;

  semaphore *fullBuffersSem = malloc(sizeof(semaphore));
  createSem(fullBuffersSem, 0);
  b->fullBuffers = fullBuffersSem;

  semaphore *emptyBuffersSem = malloc(sizeof(semaphore));
  createSem(emptyBuffersSem, theBuffSize);
  b->emptyBuffers = emptyBuffersSem;

  char charBuffer[theBuffSize];
  b->theBuffer = charBuffer;
}
コード例 #6
0
ファイル: main.c プロジェクト: Bajowy/Systemy-Operacyjne
int main (int argc, char **argv)
{
	struct sembuf buf = {0, 0, 0}; //declaration buf structure
	
	int semid = createSem(PATH, PROJECTID, SEMVALUE, IPC_CREAT | WRITEREADATT); //create semaphore

	switch(fork())
	{
		case -1: //if fork error
			perror(FORKERROR);
			exit(1);
			break;
		case 0: 
			printData(semid); //print process id and sem data
			buf.sem_op = CLOSE; // close semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			criticalSection(); // do sth
			printData(semid); //print process id and sem data
			buf.sem_op = OPEN; // open semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			printData(semid); //print process id and sem data
			buf.sem_op = CLOSE; // close semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			criticalSection();  // do sth
			printData(semid); //print process id and sem data
			buf.sem_op = OPEN; // open semaphore
			if(semop(semid, &buf, 1) == -1) // send cmd
			{
				perror(SEMOPERROR);
				exit(EXIT_FAILURE);
			}
			printf(PARENTEND); //end of parent
			printData(semid); //print process id and sem data
			if(wait(NULL) == -1) // wait for children
			{
				perror(WAITERROR);
				exit(EXIT_FAILURE);
			}
			printf(SEMDELETE, semid); 
			deleteSem(semid); // delete sem
			
			break;
	}
	
	return 0;
}
コード例 #7
0
ファイル: clib_log.cpp プロジェクト: koolhazz/ProxyServer
/**
 * Set the log filename.
 *
 * @param   as_file     Log filename.
 * @param   ai_pathtype Log filename path type (define CLIB_LOG_PATH_xxx).
 * @return              0: succ, !=0: fail.
 */
int clib_log::set_file( const char *as_file,
                        int         ai_pathtype )
{
    if ( NULL == as_file ) return(-1);

    //memset( ms_file,   0, sizeof(ms_file) );

    if ( ai_pathtype == CLIB_LOG_PATH_RELATIVE ) {
        snprintf( ms_file, sizeof(ms_file), "%s/%s",
                    CLIB_LOG_PATH, as_file );
    } else {
        snprintf( ms_file, sizeof(ms_file), "%s", as_file );
    } // if

    //init semopher
    int fd = open( ms_file, O_WRONLY|O_APPEND|O_CREAT, 0666 ); 
    if (fd > 0)
    {
        close(fd);
    }
    key_t ipc_key = ftok( ms_file, 0 );
    if (mi_semopen && ipc_key > 0)
    {
        createSem(ipc_key, &mi_semid, NULL);
    }

    return(0);
}
コード例 #8
0
ファイル: buffer.c プロジェクト: banga/COMP530
/*
 * Allocates size bytes for the buffer and initializes the semaphore
 * Returns 0 on success, -1 on failure to allocate memory
 */
bounded_buffer * createBuffer(size_t size) {
	if(size == 0)
		return NULL;

	bounded_buffer * b = (bounded_buffer *) malloc(sizeof(bounded_buffer));
	if(b == NULL)
		return NULL;

	b->buffer = (int *)malloc(size * sizeof(int));
	if(b->buffer == NULL)
		return NULL;

	createSem(&b->emptyBuffers, size);
	createSem(&b->fullBuffers, 0);
	b->nextIn = b->nextOut = 0;
	b->size = size;

	return b;
}
コード例 #9
0
ファイル: LibLog.c プロジェクト: ZipLee/mylog
LOG_OPT* initLog(const char* path, int level, int max_size, int use_sem)
{
	int fd = 0;
	int len = 0;
	time_t tnow;
	struct tm tm;
	key_t ipc_key;
	LOG_OPT* pLogOpt = NULL;
	char* pFilename = NULL;
		

	len = sizeof(LOG_OPT);
	if (NULL == (pLogOpt = (LOG_OPT*)calloc(1, sizeof(LOG_OPT)))){
		printf("init with malloc object NULL\n");
		return NULL;
	}

	if (level < LOG_ERROR || level > LOG_TRACE || max_size <= 0){
		pLogOpt->err_code = LOG_ERR_ARGU_WRONG;
		return NULL;
	}
	pLogOpt->level = level;
	pLogOpt->max_size = max_size;

	if (NULL == (pFilename = (char*)calloc(1, (MAX_LOG_PATH_LEN * sizeof(char))))){
		pLogOpt->err_code = LOG_ERR_MALLOC_NULL;
		return NULL;
	}
	
	if (NULL == path){
		getFileName(pFilename);
	}else{
		snprintf(pFilename, MAX_LOG_PATH_LEN, "%s", path);
	}

	fd = open(pFilename, O_WRONLY|O_APPEND|O_CREAT, 0666); 
	if (fd <= 0){
		close(fd);
		pLogOpt->err_code = LOG_ERR_FD_WRONG;
		return NULL;
	}
	pLogOpt->file_fd = fd;

	ipc_key = ftok(pFilename, 0);
	if (use_sem && ipc_key > 0){
		pLogOpt->sem_flag = use_sem;
		createSem(ipc_key, &(pLogOpt->sem_id));
	}
	
	if (NULL == g_pLogOpt)
		g_pLogOpt = pLogOpt;
	
	return pLogOpt;
}
コード例 #10
0
// creates two threads using ST, one of which increments a shared counter,
// and one of which decrements it. The counter's value is printed to stdout
// after each operation. After a certain number of operations the program
// terminates.
int main (int argc, char const *argv[]) {
	// initialize the ST library runtime
	st_init();
	
	// store an arbitrary integer
	int value = 0;
	
	// create a binary semaphore initialized to 1
	semaphore bin_sem;
	createSem(&bin_sem, 1);
	
	// which output stream to use
	FILE *output = DEFAULT_OUT;
	
	// create our init data struct
	ThreadInit thread_init = {
		output,
		&bin_sem,
		&value
	};

  //JSR
  int semValue = 1;
  int i;
  for (i = 0; i < 5; i++){
    semValue++;
    up(thread_init.bin_sem);
    printf("semValue= %d\n", semValue);
  }

  /*
	// create the increment thread
	if (st_thread_create(increment_thread_func, &thread_init, 0, 0) == NULL) {
		perror("st_thread_create for increment thread failure");
		exit(1);
	}
	
	// create the decrement thread
	if (st_thread_create(decrement_thread_func, &thread_init, 0, 0) == NULL) {
		perror("st_thread_create for decrement thread failure");
		exit(1);
	}
  */

	// main thread exits
	st_thread_exit(NULL);
	return 0;
}
コード例 #11
0
ファイル: socket.c プロジェクト: epintos/os-p1
int createIPC(int id, int sockets_qty) {


	if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == ERROR
		)
		return ERROR;

	struct sockaddr_un socket_addr;
	initialize_socket_addr(id, &socket_addr);

	if ((bind(fd, (struct sockaddr *) &socket_addr, STR_SIZE) == ERROR))
		return ERROR;

	sem_id = createSem(SEM_KEY, sockets_qty);
	setAllSem(sem_id, sockets_qty, 1);

	return EXIT_SUCCESS;

}
コード例 #12
0
ファイル: HW3.c プロジェクト: magwe25/Helms-Deep
/*
4 threads are created and wired here; the first will process the input
from INPUT and place the results in a buffer shared with the first of two string
processing threads. The first of those will replace carriage returns with spaces
and the seccond will replace pairs of asterisks with carats. Both of these threads will
place the character whether replaced or not on the next shared buffer. The final thread will
count to 80 and output while keeping the passed characters in an array that will be output

Naming convention:
rd = read
fp = first processing thread
sp = second processing thread
op = output
ex rd_fp_buf = read to first processing thread buffer, the buffer between read and first process
*/
void main(void){
	st_init();
	
	//integers so I don't get confused about the buffers' zeros
	int end = 0;
	int start = 0;
	//malloced arrays for the circular buffers
	char *rd_fp_buf = malloc(default_size * sizeof(char));
	char *fp_sp_buf = malloc(default_size * sizeof(char));
	char *sp_op_buf = malloc(default_size * sizeof(char));
	//Circular buffers for use by threads
	CircularBuffer rd_fp_cirbuf = {
		default_size,
		start,
		end,
		rd_fp_buf
	};
	CircularBuffer fp_sp_cirbuf = {
		default_size,
		start,
		end,
		fp_sp_buf
	};
	CircularBuffer sp_op_cirbuf = {
		default_size,
		start,
		end,
		sp_op_buf
	};
	
	//woo semaphores! three for each pair of threads
	semaphore rd_fp_sem;
	semaphore fp_sp_sem;
	semaphore sp_op_sem;
	//initialize 1 to make sure we can get in the first time!
	createSem(&rd_fp_sem,1);
	createSem(&fp_sp_sem,1);
	createSem(&sp_op_sem,1);

	semaphore rd_fp_fullbuffs;
	semaphore fp_sp_fullbuffs;
	semaphore sp_op_fullbuffs;
	createSem(&rd_fp_fullbuffs, 0);
	createSem(&fp_sp_fullbuffs, 0);
	createSem(&sp_op_fullbuffs, 0);
	
	semaphore rd_fp_emptybuffs;
	semaphore fp_sp_emptybuffs;
	semaphore sp_op_emptybuffs;
	//must initialize the full buffs semaphore to the correct value
	createSem(&rd_fp_emptybuffs, default_size);
	createSem(&fp_sp_emptybuffs, default_size);
	createSem(&sp_op_emptybuffs, default_size);

	//thread initiators for the various threads
	//This instantion goes on forever...
	IOThreadInit rd_thread_init = {
		//read source
		INPUT,
		//semaphores
		&rd_fp_sem,
		&rd_fp_fullbuffs,
		&rd_fp_emptybuffs,
		//circular buffer
		&rd_fp_cirbuf
	};
	ThreadInit fp_thread_init = {
		//semaphores
		&rd_fp_sem,
		&rd_fp_fullbuffs,
		&rd_fp_emptybuffs,
		&fp_sp_sem,
		&fp_sp_fullbuffs,
		&fp_sp_emptybuffs,
		//circular buffers
		&rd_fp_cirbuf,
		&fp_sp_cirbuf
	};
	ThreadInit sp_thread_init = {
		//semaphores
		&fp_sp_sem,
		&fp_sp_fullbuffs,
		&fp_sp_emptybuffs,
		&sp_op_sem,
		&sp_op_fullbuffs,
		&sp_op_emptybuffs,
		//circular buffers
		&fp_sp_cirbuf,
		&sp_op_cirbuf
	};
	IOThreadInit op_thread_init = {
		//output destination
		OUTPUT,
		//semaphores
		&sp_op_sem,
		&sp_op_fullbuffs,
		&sp_op_emptybuffs,
		//circular buffer
		&sp_op_cirbuf
	};
	
	//create the threads, finally!
	if (st_thread_create(read_thread_func, &rd_thread_init, 0, 0) == NULL){
		perror("Error creating read thread");
		exit(1);
	}
	if (st_thread_create(firstproc_thread_func, &fp_thread_init, 0, 0) == NULL){
		perror("Error creating first process thread");
		exit(1);
	}
	if (st_thread_create(secondproc_thread_func, &sp_thread_init, 0, 0) == NULL){
		perror("Error creating second process thread");
		exit(1);
	}
	if (st_thread_create(output_thread_func, &op_thread_init, 0, 0) == NULL){
		perror("Error creating output thread");
		exit(1);
	}
	
	st_thread_exit(NULL);
}
コード例 #13
0
ファイル: monitor.cpp プロジェクト: RuslanIvanov/Ruslan
int main()
{
    signal (SIGTERM, out);
    signal (SIGINT, out);

    int shmid;
    /* искать сегмент, соответствующий ключу key*/
    shmid = shmget((key_t)1234, sizeof(struct memFormat), 0666);

    if (shmid == -1)  {perror("shmget");return 0;}

    shared_memory = shmat(shmid, (void *)0, SHM_RDONLY);
    if (shared_memory == (void *)-1) {perror("shmat");return 0;}

    int sem_id = createSem(1,12345);
    if(sem_id==-1) {perror("createSem"); return 0;}
	
    if(set_semvalue(sem_id,0)==-1) {perror("set_semvalue"); return 0;}

    semaphore_p(sem_id);
    memcpy(&memf,shared_memory, sizeof(struct memFormat)); 
    semaphore_v(sem_id);

    if (shmdt(shared_memory) == -1) {perror("shmat"); return 0;}

    int size = sizeof(struct memFormat)+(memf.max*memf.sizeItem);
    printf("Moniotr attache mem size: %d + %d=%d",sizeof(struct memFormat),(memf.max*memf.sizeItem),size);

    shmid = shmget((key_t)1234, size, 0666);

    if (shmid == -1)  {perror("shmget2");return 0;}

    shared_memory = shmat(shmid, (void *)0, SHM_RDONLY);
    if (shared_memory == (void *)-1) {perror("shmat2");return 0;}

    pitem = (int*)shared_memory+sizeof(struct memFormat);
    printf("Monitor memory attached at %p,data attached at %p\n", shared_memory,pitem);

    printf("memory pid %d:\n sizeItem %d, count %d, max %d",memf.pidMaster,memf.sizeItem,memf.count,memf.max);
    sleep(1);
    while(bOut==false) 
    {        
	pitem = (int*)shared_memory+sizeof(struct memFormat);

	delay(500);
	
	int count1=0;

	if(!semaphore_p(sem_id)) {perror("semaphore_p");break;}

	memcpy(&memf,shared_memory, sizeof(struct memFormat));	
	for(int vi=0;vi<memf.count;vi++)
	{
		if(*pitem==1) count1++;
		//printf("%d.",*pitem);
		pitem++;
	}

	if(!semaphore_v(sem_id)) {perror("semaphore_v");break;}
	printf("\nnumber '1': %d.",count1);          
        
    }

    if (shmdt(shared_memory) == -1) {perror("shmat2");}
    del_semvalue(sem_id,0);
    printf("\nExit...\n");
}
コード例 #14
0
ファイル: ipcmk.c プロジェクト: AtariTeenageRiot/LUKS
int main(int argc, char **argv)
{
	int permission = 0644;
	int opt;
	size_t size = 0;
	int nsems = 0;
	int doShm = 0, doMsg = 0, doSem = 0;

	progname = program_invocation_short_name;
	if (!progname)
		progname = "ipcmk";

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	while((opt = getopt(argc, argv, "hM:QS:p:")) != -1) {
		switch(opt) {
		case 'M':
			size = atoi(optarg);
			doShm = 1;
			break;
		case 'Q':
			doMsg = 1;
			break;
		case 'S':
			nsems = atoi(optarg);
			doSem = 1;
			break;
		case 'p':
			permission = strtoul(optarg, NULL, 8);
			break;
		case 'h':
			usage(EXIT_SUCCESS);
			break;
		default:
			doShm = doMsg = doSem = 0;
			break;
		}
	}

	if(!doShm && !doMsg && !doSem)
		usage(EXIT_FAILURE);

	if (doShm) {
		int shmid;
		if (-1 == (shmid = createShm(size, permission)))
			err(EXIT_FAILURE, _("create share memory failed"));
		else
			printf(_("Shared memory id: %d\n"), shmid);
	}

	if (doMsg) {
		int msgid;
		if (-1 == (msgid = createMsg(permission)))
			err(EXIT_FAILURE, _("create message queue failed"));
		else
			printf(_("Message queue id: %d\n"), msgid);
	}

	if (doSem) {
		int semid;
		if (-1 == (semid = createSem(nsems, permission)))
			err(EXIT_FAILURE, _("create semaphore failed"));
		else
			printf(_("Semaphore id: %d\n"), semid);
	}

	return EXIT_SUCCESS;
}
コード例 #15
0
ファイル: clib_log.cpp プロジェクト: koolhazz/ProxyServer
/**
 * Initial clib_log class.
 *
 * @param   as_file     Log filename.
 * @param   as_tformat  Log timeformat, define in CLIB_LOG_TFORMAT_x.
 * @param   ai_level    Log level, log will write smaller than this level.
 * @param   ai_maxfile  Max log file number (0 mean no change file, maxsize no use).
 * @param   ai_maxsize  Max log file size (Byte, 0 mean unlimited).
 * @param   as_logtype  Log filename type, define in CLIB_LOG_TYPE_x.
 * @param   as_eol      End of line.
 * @param   ai_pathtype Log filename path type (define CLIB_LOG_PATH_xxx).
 */
clib_log::clib_log( const char *as_file,
                    int         as_sem,
                    const char *as_tformat,
                    int         ai_level,
                    int         ai_maxfile,
                    int         ai_maxsize,
                    const char *as_logtype,
                    const char *as_eol,
                    int         ai_pathtype,
                    const char *as_coloring)
{
    memset( ms_file,   0, sizeof(ms_file) );

    if ( as_file != NULL ) {
        if ( ai_pathtype == CLIB_LOG_PATH_RELATIVE ) {
            snprintf( ms_file, sizeof(ms_file), "%s/%s",
                        CLIB_LOG_PATH, as_file );
        } else {
            snprintf( ms_file, sizeof(ms_file), "%s", as_file );
        } // if

        //init semopher
        int fd = open( ms_file, O_WRONLY|O_APPEND|O_CREAT, 0666 ); 
        if (fd > 0)
        {
            close(fd);
        }
        key_t ipc_key = ftok( ms_file, 0 );
        mi_semopen = as_sem;
        if (mi_semopen && ipc_key > 0)
        {
            createSem(ipc_key, &mi_semid, NULL);
        }

    } // if ( as_file != NULL )

    if ( NULL != as_tformat ) {
        snprintf( ms_tformat, sizeof(ms_tformat), "%s", as_tformat );
    } else {
        snprintf( ms_tformat, sizeof(ms_tformat), "%s", CLIB_LOG_TFORMAT_0 );
    } // if

    if ( ai_maxfile >= 0 ) mi_maxfile = ai_maxfile;
    else mi_maxfile = 5;

    if ( ai_maxsize >= 0 ) mi_maxsize = ai_maxsize; // Byte
    else mi_maxsize = CLIB_LOG_SIZE_NORM;

    if ( ai_level >= CLIB_LOG_LEV_ERROR ) mi_level = ai_level;
    else mi_level = CLIB_LOG_LEV_ERROR;

    if ( NULL != as_logtype ) {
        snprintf( ms_logtype, sizeof(ms_logtype), "%s", as_logtype );
    } else {
        snprintf( ms_logtype, sizeof(ms_logtype), "%s", CLIB_LOG_TYPE_NOR );
    } // if

    if ( NULL != as_eol ) {
        snprintf( ms_eol, sizeof(ms_eol), "%s", as_eol );
    } else {
        snprintf( ms_eol, sizeof(ms_eol), "%s", CLIB_LOG_EOL_LF );
    } // if

    //set_coloring_file
    set_coloring_file(as_coloring);
}
コード例 #16
0
ファイル: HW3.c プロジェクト: jsreese92/operating_Systems
main(){
  // initialize the ST library runtime, necessary for up() and down()
  st_init();

  //BoundedBuffer into which input from stdin is stored
  BoundedBuffer theInput;
  createBuffer(&theInput, MAX_BUFF_SIZE);

  // create a binary semaphore for use with input thread
  semaphore input_sem;
  createSem(&input_sem, 1);

  ThreadInit getInputThread = {
    NULL, // no input buffer for getInput thread, comes from stdin
    &theInput, // puts data from stdin into BoundedBuffer theInput 
    NULL, //no "from" semaphore
    &input_sem //mutual exclusion for input buffer
  };

  // create input thread
  if (st_thread_create(getInput, &getInputThread, 0, 0) == NULL){
    perror("st_thread_create for getInput failure");
    exit(1);
  }

  // BoundedBuffer into which processed data w/o newlines are stored
  BoundedBuffer newLinesProcessed;
  createBuffer(&newLinesProcessed, MAX_BUFF_SIZE);
  
  // create binary semaphore for use with newline thread
  semaphore nl_sem;
  createSem(&nl_sem, 1);

  ThreadInit nlToSpaceThread = {
    &theInput, // processes input from the BoundedBuffer theInput
    &newLinesProcessed, // puts processed data into BB newLinesProcessed
    &input_sem, //mutual exclusion for input buffer
    &nl_sem // mutual exclusion for processed newlines buffer
  };

  //create newline processing thread
  if (st_thread_create(newlineToSpace, &nlToSpaceThread,0,0) == NULL){
    perror("st_thread_create for newlineToSpace failure");
    exit(1);
  }

  // BoundedBuffer into which processed data after asterisks are handled go
  BoundedBuffer caratsProcessed;
  createBuffer(&caratsProcessed, MAX_BUFF_SIZE);
  
  // create binary semaphore for use with newline thread
  semaphore carat_sem;
  createSem(&carat_sem, 1);

  ThreadInit caratThread = {
    &newLinesProcessed, // buffer from wich input is processed
    &caratsProcessed, // puts processed data into BB caratsProcessed
    &nl_sem, // for mutual exclusion in previous buffer
    &carat_sem // for mutual exclusion in processed carat buffer
  };

  // create asterisks to carat processing thread
  if (st_thread_create(asterisksToCarat, &caratThread,0,0) == NULL){
    perror("st_thread_create for newlineToSpace failure");
    exit(1);
  }

  ThreadInit printThread = {
    &caratsProcessed, // buffer from which input is processed
    NULL, // no output buffer, just printing to stdout
    &carat_sem, // for mutual exclusion in previous buffer
    NULL // no mutex needed, just printing to stdout
  };

  // create print thread
  if (st_thread_create(print80CharLines, &printThread,0,0) == NULL){
    perror("st_thread_create for print80CharLines failure");
    exit(1);
  }

  // exit main thread
  st_thread_exit(NULL);
}
コード例 #17
0
ファイル: simulation.c プロジェクト: epintos/os-p1
int main(int argc, char *argv[]) {

	initializeSigHandler();

	setpgid(0, 0);
	int i = 0;
	int ret = 0;
	pid_t pid;
	cmpQty = argc - 2;
	cmp = malloc(sizeof(company*) * cmpQty);
	map = malloc(sizeof(graph));
	sem_id = createSem(SEM_CREAT_KEY, cmpQty + SEM_QTY);
	setAllSem(sem_id, cmpQty + SEM_QTY, 0);

	if (initPIDS() == MALLOC_ERROR
	)
		return MALLOC_ERROR;

	/***PARSER***/
	if (cmp == NULL || map == NULL
	)
		return parserError(NULL, NULL, MALLOC_ERROR, NULL);
	if ((ret = parseFiles(argc, argv, map, cmp)) != EXIT_SUCCESS
	)
		return ret;

	/***INITIALIZES ARRAYS FOR THE EXECL***/

	initializeArray(&semMsg, sem_id);
	initializeArray(&procQty, ID_QTY + cmpQty);

	/***MAP AND COMPANIES CREATION***/
	if (createIPC(MAIN_ID, cmpQty + ID_QTY) == ERROR
	)
		return ERROR;

	int map_pid = 0;
	int io_pid = 0;
	int mult_pid = 0;
	if ((pid = fork()) == 0) {
		execl("io", semMsg, procQty, NULL);
		exit(1);
	} else {
		io_pid = pid;
		addPid(io_pid);
		if ((pid = fork()) == 0) {
			execl("map", semMsg, procQty, NULL);
			exit(1);
		} else {
			map_pid = pid;
			addPid(map_pid);
			if ((pid = fork()) == 0) {
				execl("multitasker", semMsg, procQty, NULL);
				exit(1);
			} else {
				mult_pid = pid;
				addPid(mult_pid);
				for (i = 0; i < cmpQty; i++) {
					if ((pid = fork()) == 0) {
						char *buf = NULL;
						int id = CMP_ID + i;
						initializeArray(&buf, id);
						execl("company", buf, procQty, semMsg, NULL);
					} else {
						addPid(pid);
					}
				}
			}
		}
	}
	upSem(sem_id, MAIN_ID);
	downSem(sem_id, IO_ID);
	downSem(sem_id, MULTITASKER_ID);
	for (i = 0; i < cmpQty; i++) {
		downSem(sem_id, CMP_ID + i);
		if (initializeCmp(cmp[i], MAIN_ID, CMP_ID + i) == ERROR
		)
			return ERROR;
	}
	downSem(sem_id, MAP_ID);
	if (initializeMap(map, MAIN_ID, MAP_ID) == ERROR) {
		return ERROR;
	}
	downSem(sem_id, MAP_ID);

	for (i = 0; i < cmpQty; i++) {
		wait(0); //Waits for all the companies to finish
	}
	kill(mult_pid, SIGTERM);
	waitpid(mult_pid, 0, 0);

	kill(map_pid, SIGTERM);
	waitpid(map_pid, 0, 0);

	kill(io_pid, SIGTERM);
	waitpid(io_pid, 0, 0);

	if (disconnectFromIPC(MAIN_ID) == ERROR) {
		destroyIPC(MAIN_ID);
	}
	destroySem(sem_id);

	/***FREES***/
	freeAll();

	return EXIT_SUCCESS;

}