Exemplo n.º 1
0
int main( int argc , char *argv[] )
{

     pid_t childpid ;
     int i , n  ;

     if ( argc != 2 ) {
          fprintf( stderr ,  "Usage : %s\n" , argv[0] )   ;
          return 1 ;
     }

     n = atoi( argv[1] ) ;

     for ( i = 1 ; i < n ; i++  )
          if ( ( childpid = fork() ) <= 0  )
               break ;

     while ( r_wait(NULL) > 0 ) ;

     fprintf( stderr , "i : %d Process ID : %ld , Parent ID : %ld \
child ID %ld \n" , i , (long)getpid() , (long)getppid() , (long)childpid ) ;
     
     return 0 ;

}
Exemplo n.º 2
0
int main(void) {
    int i;
    int n = NUM_CHILDREN;
    pid_t pids[NUM_CHILDREN];

    printf("this is the parent process, my PID is: %d\n", getpid());

    /* create the child processes */
    for (i = 0; i < n; i++) {
        /* if the process cannot be forked */
        if ((pids[i] = fork()) < 0) {
            fprintf(stderr, "can't fork, error %d\n", errno);
            abort();
            exit(1);
        }
        /* make sure the process is a child */
        else if (pids[i] == 0) {
            /* make sure it's the first child */
            if (i == 0) {
                printf("this is the first child process, my PID is: %d\n",
                        getpid());
                execl("/bin/ls", "ls", "-l", (char *)0);
                fprintf(stderr, "first child failed to execute ls, error %d\n", 
                        errno);
                exit(1);
            }
            /* make sure it's the second child */
            else if (i == 1) {
                printf("this is the second child process, my PID is: %d\n",
                        getpid());
                execl("/bin/ps", "ps", "-lf", (char *)0);
                fprintf(stderr, "second child failed to execute ps, error %d\n",
                        errno);
                exit(1);
            }
            /* make sure it's the third child */
            else if (i == 2) {
                int j;
                for (j = 0; j < 4; j++) {
                    printf("this is the third child process, my PID is: %d\n",
                            getpid());
                }
                exit(0);
            }
        }
        else {
        }
    }

    /* wait for all of the child processes */
    while (r_wait(NULL) > 0) ;
    printf("this is the parent process after my child processes with PIDS of %d, %d, and %d are terminated, the main process is terminated!\n",
            pids[0], pids[1], pids[2]);

    return 0;
}
Exemplo n.º 3
0
int main  (int argc, char *argv[]) {
   char buffer[BUFSIZE];
   char *c;
   pid_t childpid = 0;
   int delay;
   volatile int dummy = 0;
   int i, n;
   sem_t *semlockp;

   if (argc != 4){       /* check for valid number of command-line arguments */
      fprintf (stderr, "Usage: %s processes delay semaphorename\n", argv[0]);
      return 1;
   }
   n = atoi(argv[1]);
   delay = atoi(argv[2]);
   for (i = 1; i < n; i++)
      if (childpid = fork())
         break;
   snprintf(buffer, BUFSIZE,
      "i:%d  process ID:%ld  parent ID:%ld  child ID:%ld\n",
       i, (long)getpid(), (long)getppid(), (long)childpid);
   c = buffer;
   if (getnamed(argv[3], &semlockp, 1) == -1) {
      perror("Failed to create named semaphore");
      return 1;
   }
   while (sem_wait(semlockp) == -1)                         /* entry section */ 
       if (errno != EINTR) { 
          perror("Failed to lock semlock");
          return 1;
       }
   while (*c != '\0') {                                  /* critical section */
      fputc(*c, stderr);
      c++;
      for (i = 0; i < delay; i++)
         dummy++;
   }
   if (sem_post(semlockp) == -1) {                           /* exit section */
      perror("Failed to unlock semlock");
      return 1; 
   }
   if (r_wait(NULL) == -1)                              /* remainder section */
      return 1;
   return 0;
}
Exemplo n.º 4
0
void show_return_status(void) {
   pid_t childpid;
   int status;   

   childpid = r_wait(&status);
   if (childpid == -1)
      perror("Failed to wait for child");
   else if (WIFEXITED(status) && !WEXITSTATUS(status))
      printf("Child %ld terminated normally\n", (long)childpid);
   else if (WIFEXITED(status))
      printf("Child %ld terminated with return status %d\n",
             (long)childpid, WEXITSTATUS(status));
   else if (WIFSIGNALED(status))
      printf("Child %ld terminated due to uncaught signal %d\n",
             (long)childpid, WTERMSIG(status));
   else if (WIFSTOPPED(status))
      printf("Child %ld stopped due to signal %d\n",
             (long)childpid, WSTOPSIG(status));
}
Exemplo n.º 5
0
/**
 * Creates a child process to execute a command.
 * @return pid_t of the process
 */
pid_t h_run_cmd(const char *cmd,const bool wait) {
	pid_t childpid;
	char **args;

	// If invalid args, return invalid
	if (cmd == NULL) {
		errno = EINVAL;
		return -1;
	}

	// Parse the cmd into args
	h_mk_argv(cmd," \t\n",&args);

	// Spawn the new process
	childpid = fork();
	if (childpid == -1) {
		perror("Failed to fork");
		return childpid;
	}

	// If child process, execute the cmd
	if (childpid == 0) {
		execvp(args[0], &args[0]);
		perror("Child failed to execvp the command");
		exit(-1);
	}

	// Free args
	if (args == NULL) {
		if (*args != NULL) {
			free(*args);
		}
		free(args);
	}

	// Wait for it to finish (if requested)
	if (wait) {
		if (childpid != r_wait(NULL)) {
			perror("Failed to wait");
		}
	}
	return childpid;
}
Exemplo n.º 6
0
int main(int argc, char** argv) {
	if (argc != 2) {
		fprintf(stderr, "Usage: %s n\n", argv[0]);
		return 1;
	}

	char* commandline;
	int pr_count, pr_limit;
	pr_limit = atoi(argv[1]);
	pr_count = 0;
	while (fgets(commandline, MAX_CANON, stdin) != NULL) {
		if(pr_count == pr_limit) {
			fprintf(stderr, "Reached the limit, pr_count=%i, pr_limit=%i \n",
					pr_count, pr_limit);
			wait(NULL);
			pr_count--;
		}

		fprintf(stderr, "The command line is : %s", commandline);
		fprintf(stderr, "Current pr_count = %i, pr_limit = %i, pid = %i \n",
				pr_count, pr_limit, (long)getpid());
		pr_count++;
		pid_t childpid = fork();
		if(childpid == -1) {
			fprintf(stderr, "Failed to fork process.\n");
			return 0;
		} else if(childpid == 0) {
			char** tokens;
			makeargv(commandline, " ", &tokens);
			execvp(tokens[0], tokens);
			return 0;
		}
	}

	while(r_wait(NULL) > 0)	// wait for all children
		;

	return 0;
}
Exemplo n.º 7
0
int main(int argc, char** argv) 
{
	char *record;
	char *block;									//endiamesos xwros mnhmhs ston opoio ekxwroun ta block oi reducers//
	int i,j,fd;
	char buffer[56];								//pinakas ston opoion sxhmatizoume to katallhlo format gia ta pipenames//
	pid_t pid;
	int status;
	fd_set read_set, active_set;							//ta set me tous file descriptors pou xrhsimopoiei h select//
	BUFFERS *buffers;								//deikths sthn arxh twn buffers//
	
	struct sigaction sig_act;

	if (argc!=3)									//onoma ektelesimou, #Mappers, #Reducers//
	{
		printf("Usage:%s  #Mappers  #Reducers\n",argv[0]);
		return -1;
	}
	
	sig_act.sa_handler=handler1;     		    				//Signal Handler1 gia ton patera//
	sig_act.sa_flags=0;
											//prosthetw ta simata sto set tou patera.
	if ((sigemptyset(&sig_act.sa_mask ) == -1) || (sigaction(SIGINT,&sig_act,NULL) == -1 ) 
	|| (sigaction(SIGQUIT,&sig_act,NULL) == -1 ) || (sigaction(SIGTERM,&sig_act,NULL) == -1 ))
	{
	      perror("FAIL TO INSTAL  SIGNAL HANDLER FOR SIGUSR1");
	      return -1;
	}
	Mappers=atoi(argv[1]);
	Reducers=atoi(argv[2]);
	for(i=0;i<Mappers;i++)								//dhmiourgia twn pipes prin dhmiourgh8oun ta paidia//
	{
		for (j=0;j<Reducers;j++)
		{
			buffer[0]='\0';
			sprintf(buffer,".pipe.%d.%d",i+1,j+1);				
			if ( mkfifo(buffer,0666 )==-1)	
       			{
                        	perror("mkfifo");
				removepipes(Mappers,Reducers);
                        	return -1;
                	}
		}
	}
	mkdir("./output_folder",0700);					//dhmiourgoume ton output folder//
	for(i=0;i<Mappers+Reducers;i++)							//kanena paidi den exei dhmiourgh8ei akoma//							
		pids[i]=0;
	for(i=0;i<Mappers+Reducers;i++)
	{
 		pids[i]=pid=fork();
		if (pid<0)								//periptwsh apotyxias fork()//
        	{									//epeidh den 3eroume posa paidia exoun gennh8ei epityxws,ara posa prepei na//
        		perror("fork failed\n");					//skotwsoume,o pateras stelnei ena SIGINT ston eauto tou kai o handler tou patera//
               		kill(getpid(),SIGINT);						//eidopoiei ta gennhmena paidia na termatisoun//
			removepipes(Mappers,Reducers);
                        return -1;
        	}
		else if ( pid==0 )							//to paidi vgainei apo to loop ka8ws mono h Initial prepei na kanei fork()//
			break;
	}
	if (pid==0)									//an eimaste sto paidi//
	{
		sigset_t ign_signals;
		
		//prosthetw sta 3 simata sto set twn paidiwn kai meta ta mplokarw//
		if ( (sigemptyset(&ign_signals ) == -1) || (sigaddset(&ign_signals,SIGINT) == -1 ) || (sigaddset(&ign_signals,SIGQUIT) == -1 ) 
				|| (sigaddset(&ign_signals,SIGTERM) == -1 ))
		{
	      		kill(getppid(),SIGINT);
		}
		else
			sigprocmask(SIG_BLOCK,&ign_signals,NULL);

 		
		sig_act.sa_handler=handler2;     		    			 //Signal Handler2-o handler twn paidiwn//
		sig_act.sa_flags=0;
		//orizw ton handler na antistoixei sto SIGUSR1, pou stelnei o parent//
		if ((sigemptyset(&sig_act.sa_mask ) == -1) || (sigaction(SIGUSR1,&sig_act,NULL) == -1 ))
	      		kill(getppid(),SIGINT);
		for(i=0;i<Mappers+Reducers;i++)						//anazhtw ston pinaka me ta pids to 10 mhdeniko,pou ypodeiknyei th seira gennhshs//
			if (pids[i]==0)
				break;
		i++;									//auti einai i thesi mou, gia na 3exwrizw an eimai maper i reducer//
		if (i<=Mappers)								//kwdikas tou mapper//
		{
			MRIFILE* fp;
			buffers=calloc(Reducers,sizeof(struct BUFFERS));		//desmeuoume mnhmh gia tosous buffers osoi einai kai oi reducers//	
			for (j=0;j<Reducers && !error ;j++)
			{
				buffer[0]='\0';
				sprintf(buffer,".pipe.%d.%d",i,j+1);			//dinoume onoma sta pipe//
				if ( (fd=open(buffer,O_WRONLY))<0 ) 			//anoigei to pipe gia grapsimo//
       		                {
					if ( errno != EINTR )				//an yparxei la8os k den einai apo shma//
        	                        	kill(getppid(),SIGINT);			//steile to shma //
	       	                	perror("Mapper::open");				//alliws ginetai allo la8os sthn open//
					free(buffers);					//kai apodesmevoume tous porous tou mapper//
					return -1;
        	                }
				initialize(buffers, j, fd);				//arxikopoioume tous buffers//
			}
			DIR             *dip;
			struct dirent   *dit;
			if ( (dip = opendir("input_folder")) == NULL)			//anoigoume ton inputfolder//
       			{
				if ( errno != EINTR )                           	//an yparxei la8os k den einai apo shma//
                                	kill(getppid(),SIGINT);                 	//steile to shma //
                                perror("Mapper::opendir");                         	//alliws ginetai allo la8os sthn open//
        		}
			while ((dit = readdir(dip)) != NULL  &&  !error)		//oso exoume files gia diavasma//
        		{
                		if ( strncmp(dit->d_name,"file_",5) == 0)		//an oi prwtoi 5 xarakthres twn 2 autwn string einai idioi,dhladh an einai file_//
				{
					int filenumber;					//ari8mos arxeiou input//
					
					sscanf(dit->d_name,"file_%d",&filenumber);	//kanw retrieve ton ari8mo tou trexodos arxeiou//
					if ( filenumber%Mappers+1==i)			//apofasizoume me katakermatismo poios mapper 8a diavazei apo ka8e file//
					{	
						char filename[50];
						sprintf(filename,"./input_folder/%s",dit->d_name);
						fp=input_open(filename);			//anoigoume to file//
						while ( (record=input_next(fp))!= NULL )	//kai oso uparxoun eggrafes gia diavasma//
						{						//kaleitai h addrecord gia pros8hkh eggrafwn stous buffers//
							addrecord(buffers,record,partition(map(record).key,Reducers));	
						}
						input_close(fp);			//kleinoume to file//
					}
				}
			}
			closedir(dip);							//kleinoume kai ton katalogo//
			for (j=0; j<Reducers && error==0; j++)				
			{
				if ( buffers[j].curbyte != 4 ){
					if ( my_write(buffers[j].pipedesc,buffers[j].block)!= BLKSIZE )	//grafoume sto pipe oses eggrafes exoun 3emeinei//
        	                       		printf("error here\n");
				}
			}
			for (j=0;j<Reducers;j++)
                       	{
				close(buffers[j].pipedesc);				//kleinoume ta pipe afou exoume diavasei//
			}
			free(buffers);							//afou teleiwnoume me to diavasma apodesmevoume taous buffers//
		}
		else									//kwdikas tou reducer//
		{
			char **keys;
			char **values;
			char *tempkey;							//deikths sthn prwth 8esh tou pinaka twn keys//
			char **tempval;							//deikths sthn prwth 8esh tou pinaka twn values//
			int counter;
			int total_records=0;
			int memsize=100;
			int whoami;							//8esh mias diergasias ston pinaka twn paidiwn//
			whoami=i;
			char buffer[40];
			MROFILE *fp;

			sprintf(buffer,"./output_folder/file_%d",whoami-Mappers);	//ka8orismos twn files sto output folder gia ton ka8e reducer
                        fp=output_open(buffer);

			if (  (keys=calloc(memsize,sizeof(char*))) == NULL		//an exoume provlhma me th desmeush tou pinaka gia ta keys,h' ta values// 
			|| (values=calloc(memsize,sizeof(char*)))==NULL 		//h' to block ,tote//
			|| (block=calloc(BLKSIZE,sizeof(char)))==NULL )
			{
			 	kill(getppid(),SIGINT);					//stelnoume shma ston patera//
			}
			FD_ZERO(&read_set);						//mhdenizoume to set twn file descriptors twn pipe//
			for (j=0;j<Mappers;j++)
			{
				buffer[0]='\0';
				sprintf(buffer,".pipe.%d.%d",j+1,i-Mappers);	
				if ( (fd=open(buffer,O_RDONLY))<0 ) 			//anoigoume to pipe gia diavasma//
       		                {
					if ( errno != EINTR )				//an yparxei la8os kai den einai apo shma//
						kill(getppid(),SIGINT);			//tote stelnoume to shma//
        	                	perror("Reducer::open");
					break;
        	                }
				FD_SET(fd,&read_set);					//pros8etoume ton fd sto readset//
			}
			active_set=read_set;
			int closed=0;							//arxikopoioume to plh8os twn diavasmenwn fds//
			while ( error==0 && closed != Mappers)				//oso uparxoun fds sto active set kai den lavei shma//
			{
				read_set=active_set;
				int chosen;
				if ( (chosen=select(FD_SETSIZE,&read_set,NULL,NULL,NULL)) < 0) 		
				{
					if ( errno != EINTR ){
                                                kill(getppid(),SIGINT);
						error=1;
					}
					perror("select");				//alliws yparxei provlhma sth select//
					break;
				}
				else							//h select epistrefei ton katallhlo fd//
				{
					for (i = 0; i < FD_SETSIZE; i++)		//gia olous tous fds pou yparxoun mesa sto set//
					{
             					if (FD_ISSET (i, &read_set))		//an o i fd einai melos tou read set otan epistrepsei h select//
						{
							if ( (chosen=my_read(i,block))<0 )		//diavase apo ton i fd//
							{
								if ( errno != EINTR )
								{
                                         			       	kill(getppid(),SIGINT);
                                                			error=1;
                                        			}
								perror("read");
								break;
							}
							else if ( chosen==0 )			
							{
								FD_CLR (i, &active_set); 	//afairei ton i fd apo to active set//
								closed++;			//au3anetai kata ena o ari8mos twn fds pou diavasthkan//
								close(i);			//kleinei o i fd//
								if ( closed == Mappers )
									break;
							}
							else
								retrieve_records(block,&keys,&values,&total_records,&memsize);
						}
					}
				}
			}
			printf("%s\n",keys[10000]);
			printf("%d\n",total_records);
			if ( error==0 )								//an den exoume lavei shma//
			{
				sort(keys, values, total_records,compare);						
        	                tempkey=keys[0];						//o deikths tempkey deixnei sthn 1h 8esh tou pinaka twn keys//
                	        tempval=values;
                        	counter=1;
                	        for ( i=1; i<total_records; i++)
                        	{
                               		if ( compare(tempkey,keys[i]) == 0 )			//an ta kleidia se dyo diadoxikes 8eseis tou pinaka einai idia//
                                	        counter++;					//au3anetai kata 1 to plh8os twn eggrafwn me to idio kleidi//	
                       		        else							//an ta kleidia se dyo diadoxikes 8eseis tou pinaka einai diaforetika//
                                	{
						output_next(fp,reduce(tempkey,tempval,counter));//kaleitai h reduce kai grafoume to apotelesma sto output file.//
                         	                counter=1;					//epilegoume neo kleidi//
                                	        tempkey=keys[i];				//h kainouria 8esh tou tempkey//
                                        	tempval=values+i;				//h kainouria 8esh tou tempval//
                                	}
        	                }
			}
			output_close(fp);							//kleinoume to output file tou kathe reducer//
			if ( block != NULL )							//apodesmeush twn porwn tou reducer//
				free(block);
			if ( keys != NULL && values!= NULL )					//an den exei ginei la8os kata th desmeush//
			{									//apodesmeuoume olh th dunamika desmeumenh mnhmh//
				for(i=0;i<memsize;i++)						
				{
					if ( keys[i]!=NULL && values[i]!=NULL )
					{
						free(keys[i]);
						free(values[i]);
					}
				}
				free(keys);
				free(values);
			}
			for (i = 0; i < FD_SETSIZE; i++)					//kleinoume olous tous file descriptors pou vriskodai sto active set//
                              if (FD_ISSET (i, &active_set))   
					close(i);
		}	
	}
	else											//alliws an eisai ston patera,Initial process//
	{
		while ( (pid=r_wait(NULL))>0 )							//perimenei ta paidia tou na teleiwsoun// 
		{	
			fprintf(stderr,"Child %d finished\n",pid);
		}	
		removepipes(Mappers,Reducers);							//svhsimo twn pipes//
	}
	return 0;
	
}
Exemplo n.º 8
0
Arquivo: test.c Projeto: jz685/OS
int writefileback (int inode_number, char *outputdir)
{
	char* filenameTemp;
	int len, index;
	pid_t childpid;
	
	filenameTemp = Directory_Structure[inode_number].Filename;
	fprintf (stderr, "filenameTemp is %s\n", filenameTemp);
	
	len = Inode_List[inode_number].File_Size;
	fprintf (stderr, "len is %d\n", len);
	
	char* to_read = (char*) malloc(len );	
	//Read_File(inode_number, 0, length, to_read);
	FILE *fw;
	
	index = Open_File(filenameTemp);
	
	char writefilepath[100];
	char newpath[100];
	sprintf(writefilepath, "%s/%s", outputdir, filenameTemp);
	sprintf(newpath, "%s%s", writefilepath, "encd");
	fprintf (stderr, "writefilepath is %s\n", writefilepath);
	
	if (Read_File( inode_number, 0, len, to_read) > 0)
	{
		//fprintf(stderr,"%s\t", to_read);
		fw = fopen(newpath, "w");
		if(fw != NULL)
		{
			int i = 0;
			while(i < len)
			{
				fputc(to_read[i], fw);
				i++;
			}
		}else{
			fprintf(stderr,"Oops, can't open\n");
		}
		fclose(fw);
	}
	
	
	childpid = fork();	
	//error handling
	if (childpid == -1) 
	{
		perror("Failed to fork");
		return 1;
	}
	//child code
	if (childpid == 0) 
	{
		fprintf(stderr, "--------------I am the child----------------\n");
		//char filepath[100];
		//char newpath[100];
		//sprintf(filepath, "%s/%s", dir, d_name);
		//sprintf(newpath, "%s%s", filepath, "encd");
		fprintf(stderr,"writefilepath is %s \t newpath is %s\t\n", writefilepath, newpath);
		char cmd[200];
		strcpy(cmd, "base64");
		strcat(cmd, " -d ");
		strcat(cmd, newpath);
		strcat(cmd, " > ");
		strcat(cmd, writefilepath);
		execlp("/bin/bash", "bash", "-c", cmd, NULL);
		//execl("/usr/bin/base64", "base64", filepath, ">", newpath);
	}else{
		//wait
		while(r_wait(NULL) > 0)
		{
			fprintf(stderr, "Parent Wait\n");
		}
		fprintf(stderr, "--------------I am the parent----------------\n");
	}

	return 0;
}
Exemplo n.º 9
0
Arquivo: test.c Projeto: jz685/OS
//Read all files in the input directory and copy all files to mini file system
int ReadDir(const char *dir)
{
	int file_count = 0;
	int temp = 0;
	struct dirent* ptr;
	DIR* srcdir = opendir(dir);
	pid_t childpid;

	if (srcdir == NULL)
	{
		perror("opendir");
		return -1;
	}

	while((ptr = readdir(srcdir)) != NULL)										// traverse done
	{
		char* d_name;
		d_name = ptr -> d_name;

		if (ptr -> d_type & DT_DIR)									// check whether it is a directory
		{
			if(strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
			{
				char path[100];
				sprintf(path, "%s/%s", dir, d_name);
				temp = ReadDir(path);
				file_count += temp;
			}
		}else{
			printf("\n/////////////////////////START//////////////////////////\n%s/%s\n", dir, d_name);
			if (isJPG(d_name)){
				//---------------Jia------------------
				//fork
				
				childpid = fork();
				
				//error handling
				if (childpid == -1) 
				{
					perror("Failed to fork");
					return 1;
				}
				//child code
				if (childpid == 0) 
				{
					fprintf(stderr, "--------------I am the child----------------\n");
					char filepath[100];
					char newpath[100];
					sprintf(filepath, "%s/%s", dir, d_name);
					sprintf(newpath, "%s%s", filepath, "encd");
					fprintf(stderr,"filepath is %s \t newpath is %s\t\n", filepath, newpath);
					char cmd[200];
					strcpy(cmd, "base64 ");
					strcat(cmd, filepath);
					strcat(cmd, " > ");
					strcat(cmd, newpath);
					execlp("/bin/bash", "bash", "-c", cmd, NULL);
					//execl("/usr/bin/base64", "base64", filepath, ">", newpath);
				}else{
					//wait
					while(r_wait(NULL) > 0)
					{
						fprintf(stderr, "Parent Wait\n");
					}
					fprintf(stderr, "--------------I am the parent----------------\n");
					//---------------end jia---------------
					//--------------------Create---------------------------
					int f = Create_File(d_name);
					//printInode(Inode_List[Superblock.next_free_inode-1]);
					if(f == -3)
					{
						printf("File could not be added to Directory.\n");
						continue;
					}else if (f == -2)
					{
						printf("File could not be written to the new inode.\n");
						continue;
					}else if (f == -1)
					{
						printf("File already existed in directory.\n");
						continue;
					}else{
						//printf("ptr->d_name: %s\n", d_name);			// #################
						file_count++;
						//------------------------------Copy image to mini file system-------------------------------------------
						FILE *fp;
						int ch;
						//fprintf(stderr, "d_name is: %s\n", d_name);
						char filepath[100];
						sprintf(filepath, "%s/%s", dir, d_name);
						//--------------jia--------------------
						char newpath[100];
						sprintf(newpath, "%s%s", filepath, "encd");
						fprintf(stderr,"filepath is %s \t newpath is %s\t\n", filepath, newpath);
						fp = fopen(newpath, "r");
						///--------------end jia----------------
						
						//fp = fopen(filepath, "r");
						if (fp == NULL) {
							fprintf(stderr, "Cannot open %s/%s .....\n", dir, d_name);
							break;														// what we should do if could not read file!!!!!!!!!!!!!!
						}else{
							//------------------------------Copy file to mini_filesystem---------------------------------------
							fseek(fp, 0L, SEEK_END);
							int sz = ftell(fp);
							fseek(fp, 0L, SEEK_SET);
							char* to_write = (char*) malloc(sizeof(char)*sz);
							int i = 0;
							while( (ch = fgetc(fp)) != EOF )
							{
								to_write[i] = ch;
								//fprintf(stderr, "%c\t", ch);
								i++;
							}
							//fprintf(stderr, "\nto_write is: %s\n", to_write);
							Write_File(Search_Directory(d_name), 0, to_write, sz);
							fprintf(stderr,"---------------\n");
							printInode(Inode_List[Superblock.next_free_inode-1]);
							fprintf(stderr,"---------------\n/////////////////////////END///////////////////////////\n");
						}
						
					}
				}
			}else{
				printf("The file is not JPG file, skipped it.\n");
			}
			
		}
		
	}
	closedir(srcdir);
	return file_count;
}
Exemplo n.º 10
0
int main(int argc, char *argv[]) {
    u_port_t portnumber;
    pthread_t *tid;
    int i;
    int pos = 0;
    int flag = 0;
    int error;
    int *return_value;
    int child;
    char path[] = "/usr/bin/gcc";
    char **snew;

    if((snew = (char **)malloc(sizeof(char *)*(argc + 3))) == NULL) {
        perror("Unable to allocate exec arguments");
        return 0;
    }

    *snew = path;
    pos = (argc + 1)/2;

    for(i = 0; i < argc-2; i+=2) {
        const char *str_name = argv[i+3];
        char *name_o;

        if((name_o = malloc(strlen(str_name) + 1)) == NULL)
            return 0;

        strcpy(name_o, str_name);
        strcat(name_o, ".o");

        *(snew + i/2 + 1) = name_o;
    }
    *(snew + pos) = "-o";
    *(snew + pos + 1) = argv[3];
    *(snew + pos + 2) = 0;
    if (argc%2 != 1 && argc <= 1) {
        fprintf(stderr, "Usage: %s port {hostname filename}\n", argv[0]);
        return 1;
    }

    fprintf(stderr, "networkcompile written by Zijing Mao\n");

    portnumber = (u_port_t)atoi(argv[1]);

    if((tid = (pthread_t *)calloc(argc - 1, sizeof(pthread_t))) == NULL) {
        perror("Failed to allocate.");
        return 0;
    }

    for(i = 0; i < argc-2; i+=2) {
        struct connectpara conn_para;
        conn_para.portnumber = portnumber;
        conn_para.hostname = argv[i + 2];			/* get the host name */
        conn_para.filename = argv[i + 3];			/* get the file name */
        if (error = pthread_create(tid + i, NULL, threadconnect, &(conn_para))) {
            fprintf(stderr, "Failed to create thread: %s\n", strerror(error));
            return 0;
        }
        fprintf(stderr, "%s\n", argv[i]);
    }

    for (i = 0; i < argc-2; i+=2) {
        if(error = pthread_join(tid[i], (void **)&return_value)) {
            perror("Failed to join thread.\n");
            return 0;
        }
        if(*return_value == 1) {			/* if one thread failed to compile, then return */
            fprintf(stderr, "return value:	1\n");
            flag = 1;
        }
        else {
            fprintf(stderr, "return value:	0\n");
        }
    }

    if(flag == 1) {
        fprintf(stderr, "Errors occur in compiling.\n");
        return 0;
    }

    child = fork();

    if(child < 0) {
        perror("Fail to fork\n");
        return 0;
    }

    if(child == 0) {			/* Child code */
        execvp(path, snew);
        perror("Child failed to exec the command");
        return 0;
    }

    for(i = 1; i < pos; i++) {	/* free all the allocated memory */
        free(*(snew + i));
    }
    free(snew);

    while(r_wait(NULL) > 0);	/* wait for all children */

    free(tid);
    return 1;
}
Exemplo n.º 11
0
int main(int argc, char *argv[]){
	if(argc < 2){
		fprintf (stderr, "Usage: %s command filename1 [filename2] ...\n", argv[0]);
		return 0;
	}

	int i;
	int return_value;
	int child;
	char path[] = "/usr/bin/gcc";	
	char **snew;

	if((snew = (char **)malloc(sizeof(char *)*(argc + 3))) == NULL){
		perror("Unable to allocate exec arguments");
		return 0;
	}
	
	/* to implement snew as the parameter used in execvp*/
	/* char *snew[] = {"gcc", "filename1.o", "filename2.o" ,"-o", "filename1", 0}; */
	*snew = path;
	for(i = 1; i < argc; i++){
		const char *str_name = argv[i];
		char *name_o;
		
		if((name_o = malloc(strlen(str_name) + 1)) == NULL)
			return 0;

		strcpy(name_o, str_name);
		strcat(name_o, ".o");

		*(snew + i) = name_o;
	}
	*(snew + argc) = "-o";
	*(snew + argc + 1) = argv[1];
	*(snew + argc + 2) = 0;


	
	fprintf(stderr, "makeserial written by Zijing Mao\n");

	for(i = 1; i < argc; i++){
		return_value = compile(path, argv[i]);

		fprintf(stderr, "%s\n", argv[i]);		
		fprintf(stderr, "%s %d\n", argv[i], return_value);

		if(return_value == 0){
			perror("Compile failed to compile an object");
			return 0;
		}
	}

	child = fork();
	
	if(child < 0){
		perror("Fail to fork\n");
		return 0;
	}

	if(child == 0){			/* Child code */
		execvp(path, snew);
		perror("Child failed to exec the command");
		return 0;
	}

	for(i = 1; i < argc; i++){	/* free all the allocated memory */
		free(*(snew + i));
	}
	free(snew);

	while(r_wait(NULL) > 0);	/* wait for all children */

	return 1;
}