//	MAIN function
int main()
{
	pid_t pid;
	int i, valueFromChild=-1;

	//	forking child process
	pid = fork();

	if(pid < 0) {	//	if child not created
		printf("Error! child not created!");
	}
	else if(pid == 0) {	// if child created, goto "childProcess()" function
		childProcess();
	}

	//	parent process (MAIN is the parent process, as it's forking the child)
	printf("Parent is waiting....\n"); // parent will wait for the child process to complete.

	wait(&valueFromChild);	// waiting for child. Then Storing the SIGNAL from Exit() of ChildProcess, which will be the number that is being passed.

	printf("Child Exited. Parent PID:\t%d\n", getpid());

	int num = valueFromChild / 255; // converting SIGNAL to Integer.

	//fibonacci series
	for(i=0; i<num; i++)
		printf("%lg\n", fibo(i));
	

	printf("\n\n");
	return 0;
}
Example #2
0
int main(){
	int i=0;
	pid_t pid;
	
	/*if( (pid = fork() ) != 0){
		printf("%d\n\n",pid);
		printf("Error : child process creation unsuccessful\n");
		///_exit(0);
	}*/
	
	pid=fork();
	
	printf("Outside pid : %d\n\n",pid);
	if(pid == 0){
		printf("\n\n\n");
		childProcess();
		//sleep(10000000);
		printf("Exiting from child\n");
		_exit(0);
	}
	
	else{
		printf("\n\n\n");
		parentProcess();
		//sleep(10000000);
		printf("Exiting from parent\n");
		_exit(0);
	}
	
	return 0;
}
//	MAIN function
int main()
{
	pid_t pid;
	int valueFromChild=-1;

	//	forking child process
	pid = fork();

	if(pid < 0) {	//	if child not created
		printf("Error! child not created!");
	}
	else if(pid == 0) {	// if child created, goto "childProcess()" function
		childProcess();
	}

	//	parent process (MAIN is the parent process, as it's forking the child)
	printf("Parent is waiting....\n"); // parent will wait for the child process to complete.

	wait(&valueFromChild);	// waiting for child. Then Storing the SIGNAL from Exit() of ChildProcess, which will be the number that is being passed.

	printf("Child Exited. Parent PID:\t%d\n", getpid());

	int num = valueFromChild / 255; // converting SIGNAL to Integer.

	//factorial
	printf("factorial of %d is...\t%lg",num, fact(num)); // showing factorial by fact() function call
	

	printf("\n\n");
	return 0;
}
Example #4
0
int main(int argc, char *argv[]){
	int pid;
	

	if((pid=fork()) == 0)
	{	
		childProcess();
	}else{
		parentProcess();
	}
}
Example #5
0
int main()
{
	//allocDealloc();					//The function for allocation and deallocation is there but not used
	srand(time(NULL));
	pid_t pd1,pd2,pd;	
	char choice[10];
	int variable=0,status;
	pd1=fork();							//First child Process
	if (pd1<0)
		printf("Forking process failed\n");
	else if (pd1==0)
		childProcess(1);
		
	pd2=fork();							//Second child Process
	if (pd2<0)
		printf("Forking process failed\n");
	else if (pd2==0)
		childProcess(2);
	parentProcess();
	pd=wait(&status);					//Waits for any of the two child process to finish 
	printf("Parent detects child process %d was done first\n",pd);
	pd=wait(&status);					//Waits for second process to finish
	printf("Parent detects child process %d is done \n",pd);
	printf("Parent exits\n");
	wait_for_time(1);					//Wait for a given time
	printf("Do you want to execute any file yes or no\n");
	scanf("%s",choice);
	if (strcmp(choice,"yes")==0) 
	{
		printf("The program is moving over to executing another binary\n");		//executes another file
		execute();
	}
	else
	{
		printf("That's all");
		exit(0);
	}

	return 0;
}
Example #6
0
void makeChildren( const int procTotal, const bool isMutex ) {
	for ( int i = 1; i <= procTotal; i++ ) {
		Process process = { procTotal, PARENT_ID, isMutex, 0, 0, 0, 0 };
		TList* list = ( TList* ) malloc( sizeof( TList ) );
		list -> head = NULL;
		list -> tail = NULL;
		process.list = list;

		if ( fork() == 0 ) {
			process.localId = i;
			childProcess( &process );
			break; // To avoid fork() in a child
		} else if ( i == procTotal ) { // The last child has been created
			parentProcess( &process );
		}
	}
}
Example #7
0
File: main.c Project: esussman/Labs
int main(int argc, char ** argv)
{
	
	int pid = fork();
	
	if(pid == 0)
		childProcess(argv);
	else if(pid != -1)
		parentProcess(pid);
	else
	{
		printf("Failure");
	}
		

	return 0;
}
Example #8
0
File: gui.c Project: NgoHuy/unikey
//----------------------------------------------------
void ximTerminatedHandler(int signum)
{
  sigset_t sigs;

  waitpid(WAIT_ANY, NULL, WNOHANG); //to kill zombies

  sigemptyset(&sigs);
  sigaddset(&sigs, SIGCHLD);
  sigprocmask(SIG_BLOCK, &sigs, NULL);

  if (XimLaunchOk) {
    XimLaunchOk = False;
    ChildPid = childProcess();
    if (ChildPid > 0)
      fputs("Unikey XIM server reloaded!\n", stderr);
  }
}
//	MAIN
int main() 
{
	int fd[2];	// 2 file decriptors for two sides (output and input)
	int pid; 	// for getting the status of the child to be forked

	pipe(fd);	//	creating a pipe.

	pid = fork();	//	forking a new child process

	if(pid == -1)
		printf("Error in creating Child!\n");
	else if(pid == 0)
		childProcess(fd);
	else
		parentProcess(fd);

	return 0;
}
Example #10
0
int main (int argc, char** argv) {
	//
	// PREPARATION: check for address and port arguments
	if (argc != 3) {
		printTime();
		printf("ERROR in PID#%d:\n\tInvalid number of arguments (2).\n\tTerminating.\n", getpid());
		return 1;
	}
	int port = atoi(argv[2]);
	// END OF PREPARATION
	//

	//
	//	SETTING UP CONNECTION WITH SERVER
	int status, socket_fd;
	struct sockaddr_in server_addr;

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	if (inet_pton(AF_INET, argv[1], &server_addr.sin_addr) < 0) {
		printTime();
		printf("ERROR in PID#%d:\n\tCouldn't set IP address.\n\tTerminating.\n", getpid());
		return 2;
	}
	if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printTime();
		printf("ERROR in PID#%d:\n\tsocket() failed.\n\tTerminating.\n", getpid());
		return 3;
	}
	if (connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
		printTime();
		printf("ERROR in PID#%d:\n\tconnect() failed.\n\tTerminating.\n", getpid());
		return 4;
	}
	printTime();
	printf("lyrebird.client: PID %d connected to server %s on port %s.\n", getpid(), argv[1], argv[2]);
	//	CONNECTION WITH SERVER IS SUCCESSFUL
	//

	//
	//	INITIALIZING CHILD PROCESSES
	// find number of available cores
	int available_cores = sysconf(_SC_NPROCESSORS_ONLN) - 1;
	// if single core, create one child process
	if (available_cores == 0) available_cores = 1;

	// initialize n-1 child processes (n = num of cores)
	// associate children with respective pipes
	int pid[available_cores];
	int pipes[2*available_cores][2];
	int child_check = 0;
	int i, j;

	for (i = 0; i < available_cores; i++) {
		// create pipes for communication
		// first pipe is for parent -> child
		// second pipe is for child -> parent
		if (pipe(pipes[2*i]) == -1) {
            pid[i] = -1;
            continue;
        }
        // use fcfs with blocking pipes [use select()]
        if (pipe(pipes[2*i+1]) == -1) {
	        close(pipes[2*i][0]);
	        close(pipes[2*i][1]);
	        pid[i] = -1;
	        continue;
	    }
	    // fork() after successful pipe creation
	    pid[i] = fork();
	    // failed fork(), close associated pipes and continue with next children
	    if (pid[i] < 0) {
	    	close(pipes[2*i][0]);
	    	close(pipes[2*i][1]);
	    	close(pipes[2*i+1][0]);
	    	close(pipes[2*i+1][1]);
	    }
	    // child process
	    else if (pid[i] == 0) {
	    	// close pipes belonging to other child processes
	    	int j;
	    	for (j = i-1; j > -1; j--) {
	    		close(pipes[2*j][1]);
	    		close(pipes[2*j+1][0]);
	    	}
	    	// close pipes used by parent process
	    	close(pipes[2*i][1]);
	    	close(pipes[2*i+1][0]);
	    	child_check = 1;
	    	break;
	    }
	    // parent process
	    else {
	    	// close pipes used by child process
	    	close(pipes[2*i][0]);
	    	close(pipes[2*i+1][1]);
	    }
	}
	//	FINISHED INITIALIZING CHILD PROCESSES
	//

	//
	//	CHILD PROCESS BEGINS HERE
	if (child_check == 1) {
		childProcess(pipes[2*i][0], pipes[2*i+1][1]);
	}
	//	CHILD PROCESS ENDS HERE
	//

	//
	//	PARENT PROCESS BEGINS HERE
	else {
		// initialize variables
		fd_set fd_read_list;
		fd_set fd_copy_list;
		int num_bytes, length;
		int status = -1;
		int fd_max = 0;
		char *input_filename, *output_filename, *filenames, *filename_ptr;
		char comparison[2100];
		char buffer[1024];
		
		// include all child->parent pipes into the fd_read_list
		for (i = 0; i < available_cores; i++) {
			if (pid[i] != -1) {
				FD_SET(pipes[2*i+1][0], &fd_read_list);
				if (fd_max < pipes[2*i+1][0]) fd_max = pipes[2*i+1][0];
			}
		}
		// send negative integer to show initial ready status
		send(socket_fd, &status, sizeof(int), 0);

		// main loop
		while (1) {
			// check if there is still at least one child process hasn't crashed
			status = 0;
			for (i = 0; i < available_cores; i++) {
				if (pid[i] > 0) {
					status = 1;
					break;
				}
			}
			if (status == 0) break;

			// filenames = malloc(sizeof(char)*2100);
			// if (filenames == NULL) break;
			// memset(filenames, 0, sizeof(char)*2100);
			// filename_ptr = filenames;

			// // receive filename from server
			// if ((num_bytes = recv(socket_fd, &status, sizeof(int), 0)) == -1) {
			// 	free(filenames);
			// 	break;
			// }
			// if (status == -1) {
			// 	free(filenames);
			// 	break;
			// }
			// recv(socket_fd, filenames, status, 0);

			// if (filenames == NULL) {
			// 	status = -1;
			// 	send(socket_fd, &status, sizeof(int), 0);
			// 	free(filename_ptr);
			// 	continue;
			// }

			// input_filename = strsep(&filenames, " ");
			// output_filename = strsep(&filenames, "\n");
			// if (input_filename == NULL || output_filename == NULL) {
			// 	status = -1;
			// 	send(socket_fd, &status, sizeof(int), 0);
			// 	free(filename_ptr);
			// 	continue;
			// }

			fd_copy_list = fd_read_list;
			if (select(fd_max+1, &fd_copy_list, NULL, NULL, NULL) == -1) {
				free(filenames);
				break;
			}

			for (i = 0; i <= fd_max; i++) {
				// check if the ith file descriptor is ready to be read from
				if (FD_ISSET(i, &fd_copy_list)) {
					filenames = malloc(sizeof(char)*2100);
					if (filenames == NULL) break;
					memset(filenames, 0, sizeof(char)*2100);
					filename_ptr = filenames;

					// receive filename from server
					if ((num_bytes = recv(socket_fd, &status, sizeof(int), 0)) == -1) {
						free(filenames);
						break;
					}
					if (status == -1) {
						free(filenames);
						break;
					}
					recv(socket_fd, filenames, status, 0);
					input_filename = strsep(&filenames, " ");
					output_filename = strsep(&filenames, "\n");
					if (input_filename == NULL || output_filename == NULL) {
						status = -1;
						send(socket_fd, &status, sizeof(int), 0);
						free(filename_ptr);
						continue;
					}

					for (j = 0; j < available_cores; j++) if (pipes[2*j+1][0] == i) break;
					num_bytes = read(i, &status, sizeof(status));	// filename length
					// child process has encountered an error that has caused an exit
					if (num_bytes == 0) {
						FD_CLR(i, &fd_read_list);
						confirmTermination(pid[j]);
						pid[j] = -1;
					}
					if (status != -1) {
						read(i, buffer, status);						// filename
						read(i, &status, sizeof(status));				// result
						length = strlen(buffer) + 1;
						send(socket_fd, &length, sizeof(int), 0);
						send(socket_fd, buffer, length, 0);				// filename
						send(socket_fd, &status, sizeof(status), 0);	// result
						send(socket_fd, &pid[j], sizeof(int), 0);		// pid
					}
					else send(socket_fd, &status, sizeof(int), 0);
					// ready for next file
					status = strlen(input_filename) + 1;
					write(pipes[2*j][1], &status, sizeof(status));
		        	write(pipes[2*j][1], input_filename, status);
		        	status = strlen(output_filename) + 1;
		        	write(pipes[2*j][1], &status, sizeof(status));
		        	write(pipes[2*j][1], output_filename, status);
		        	free(filename_ptr);
		        	continue;
				}
			}
			// recv() failed
			if (i != fd_max+1) break;
		}
		// completion or failure event has caused the termination of the program
		for (i = 0; i < available_cores; i++) {
			// if child process had already previously crashed, skip
			if (pid[i] < 0) continue;
			close(pipes[2*i][1]);		// close write pipe
			close(pipes[2*i+1][0]);		// close read pipe
			confirmTermination(pid[i]);
		}
	}
	printTime();
	printf("lyrebird client: PID %d completed its tasks and is exiting successfully.\n", getpid());
	//	PARENT PROCESS ENDS HERE
	//

	return 0;

}
Example #11
0
File: gui.c Project: NgoHuy/unikey
//------------------------------------------------------
int main(int argc, char **argv)
{
  XSizeHints *sizeHints;
  XWMHints *wmHints;
  XClassHint *classHints;
  XTextProperty windowNameP, iconNameP;
  char *windowName = "UniKey GUI";
  char *iconName = "UniKey";
  XSetWindowAttributes attrs;
  Bool setXim = False;
  int i;
  pid_t pid;

  progname = argv[0];

  for (i = 1; i < argc; i++) {
    if (!strcmp(argv[i], "-display")) {
      DisplayName = argv[++i];
    }
    else if (!strcmp(argv[i], "-xim")) {
      setXim = True;
      strcpy(XimPath, argv[++i]);
    }
    else if (!strcmp(argv[i], "-macro")) {
      MacroFile = argv[++i];
    }
    else if (!strcmp(argv[i], "-config")) {
      ConfigFile = argv[++i];
    }
    else if (!strcmp(argv[i], "-locales") || !strcmp(argv[i], "-l")) {
      XimLocales = argv[++i];
    }
    else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h")) {
      usage();
      exit(0);
    }
    else if (!strcmp(argv[i], "-version") || !strcmp(argv[i], "-v")) {
      showVersion();
      exit(0);
    }
    else {
      puts("Wrong options! Run \"unikey -h\" for help\n");
      exit(-1);
    }
  }

  if (!setXim)
    getXimPath();
  
  pid = fork();
  if (pid > 0)
    exit(0);
  else if (pid < 0) {
    fputs("failed to launch new child process\n", stderr);
    exit(-1);
  }

  getOptions();

  if (!(sizeHints = XAllocSizeHints())) {
    fprintf(stderr, "%s: failure allocating memory\n", progname);
    exit(0);
  }

  if (!(wmHints = XAllocWMHints())) {
    fprintf(stderr, "%s: failure allocating memory\n", progname);
    exit(0);
  }
  
  if (!(classHints = XAllocClassHint())) {
    fprintf(stderr, "%s: failure allocating memory\n", progname);
    exit(0);
  }

  if ((display = XOpenDisplay(DisplayName)) == NULL) {
    fprintf(stderr, "Can't Open Display: %s\n", XDisplayName(DisplayName));
    XCloseDisplay(display);
    exit(1);
  }

  StartTime = time(0);
  RootWindow = DefaultRootWindow(display);
  setRootPropMask();
  getSyncAtoms();

  if (!singleLaunch()) {
    //check if previous instance is hidden
    if (!UkGetPropValue(AGUIVisible, 0)) {
      //wake up
      UkSetPropValue(AGUIVisible, 1);
      XFlush(display);
    }
    else {
      UkSetPropValue(ARaiseWindow, 1);
      XFlush(display);
      fputs("An instance of unikey has already started!\n", stderr);
    }
    exit(1);
  }

  UkSetPropValue(AGUIVisible, 1);
  UkGUIVisible = 1;

  /* get screen size from display structure macro */
  ScreenNum = DefaultScreen(display);
  displayWidth = DisplayWidth(display, ScreenNum);
  displayHeight = DisplayHeight(display, ScreenNum);
  MainColormap = DefaultColormap(display, ScreenNum);

  // MainWinX = displayWidth-MainWinWidth-50;
  // MainWinY = displayHeight-MainWinHeight-50;
  getInitPos();

  MainWindow = XCreateSimpleWindow(display, DefaultRootWindow(display),
				   MainWinX,
				   MainWinY,
				   MainWinWidth, MainWinHeight,
				   0, WhitePixel(display, ScreenNum),
				   WhitePixel(display, ScreenNum));
  attrs.override_redirect = True;
  XChangeWindowAttributes(display, MainWindow, CWOverrideRedirect, &attrs);

  if (MainWindow == (Window)NULL) {
    fprintf(stderr, "Can't Create Window\n");
    exit(1);
  }

  // Setup window properties
  sizeHints->flags = PPosition | PSize | PMinSize;
  sizeHints->min_width = MainWinWidth;
  sizeHints->min_height = MainWinHeight;

  if (XStringListToTextProperty(&windowName, 1, &windowNameP) == 0) {
    fprintf( stderr, "Structure allocation for windowName failed.\n"); 
    exit(-1);
  }

  if (XStringListToTextProperty(&iconName, 1, &iconNameP) == 0) {
    fprintf( stderr, "Structure allocation for iconName failed.\n"); 
    exit(-1);
  }

  wmHints->initial_state = NormalState;
  wmHints->input = True;
  wmHints->flags = StateHint | InputHint;

  classHints->res_name = progname;
  classHints->res_class = "UnikeyWindow";

  XSetWMProperties(display, MainWindow, &windowNameP, &iconNameP, 
		   argv, argc, sizeHints, wmHints, 
		   classHints);

  XChangeProperty(display, MainWindow, 
		  _NET_WM_WINDOW_TYPE, XA_ATOM, 32, PropModeReplace, 
		  (unsigned char *)&_NET_WM_WINDOW_TYPE_DOCK, 1);

  //  XStoreName(display, im_window, "Unikey");
  XSetTransientForHint(display, MainWindow, MainWindow);
  XSelectInput(display, MainWindow, 
     StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask |
     VisibilityChangeMask | PointerMotionMask | PropertyChangeMask);
  
  allocXResources();
  getInitSettings();

  XMapWindow(display, MainWindow);
  UkSetPropValue(AGUIPosX, MainWinX);
  UkSetPropValue(AGUIPosY, MainWinY);

  signalSetup();
  ChildPid = childProcess();

  UkLoopContinue = 1;
  while (UkLoopContinue) {
    XEvent event;
    XNextEvent(display, &event);
    /*
      if (XFilterEvent(&event, None) == True) {
      continue;
      }
    */
    MyXEventHandler(MainWindow, &event);
  }
  cleanup();
  return 0;
}
Example #12
0
int main(int argc, char *argv[])
{
	int i, j, m, n, k, pid, total = 0, errorCheck = FALSE;
	/* 2D integer arrays to point to shared memory block. */
	int *matrixA_ptr = NULL, *matrixB_ptr = NULL, *matrixC_ptr = NULL;
	/* Names of the shared memory objects. */
	char *matrixA = "matrixA", *matrixB = "matrixB", *matrixC = "matrixC", 
		*subtotal = "subtotal";
	Shared *ptr;

	/* Error check the number of command line arguements. */
	if (argc != 6)
	{
		printf("Incorrect number of command line arguements!\n");
		errorCheck = TRUE;
	}

	/* If there was the correct number of command line arguments
	   then continue with the program. */
	if (errorCheck != TRUE)
	{
		/* Convert command-line args from string to int. */
		m = atoi(argv[3]);
		n = atoi(argv[4]);
		k = atoi(argv[5]);

		if (m < 0 || n < 0 || k < 0)
		{
			printf("One or more matrix dimensions are invalid!\n");
			return 0;
		}

		/* Create shared memory objects. */
		matrixA_ptr = (int*)createMemory(matrixA, sizeof(int)*m*n);
		matrixB_ptr = (int*)createMemory(matrixB, sizeof(int)*n*k);
		matrixC_ptr = (int*)createMemory(matrixC, sizeof(int)*m*k);
		ptr = (Shared*)createMemory(subtotal, sizeof(Shared));

		/* Read matrix files. */
		readMatrix(argv[1], m, n, matrixA_ptr);
		readMatrix(argv[2], n, k, matrixB_ptr);

		/* Initialise semaphores. */
		sem_init(&ptr->mutex, 1, 1);
		sem_init(&ptr->empty, 1, 1);
		sem_init(&ptr->full, 1, 0);

		/* Kills zombie processes. */
		signal(SIGCHLD, SIG_IGN);

		/* Create m child processes. */
		for (i = 0; i < m; i++)
		{
			pid = fork();
			/*Fork error*/
			if (pid < 0)
			{
				perror("Fork Failed");
				return 0;
			}
			/*Do child processing*/
			else if (pid == 0)
			{
				childProcess(matrixA_ptr, matrixB_ptr, matrixC_ptr, ptr, i, n, k);
				exit(0);
			}
		}
		/*Parent Process*/
		for (j = 0; j < m; j++)
		{
			sem_wait(&ptr->full);
			sem_wait(&ptr->mutex);
			/*Consume buffer*/
			printf("Subtotal produced by process with ID %d: %d\n",ptr->process, ptr->subtotal);
			total += ptr->subtotal;
	      	sem_post(&ptr->mutex);
	      	sem_post(&ptr->empty);
		}
		printf("Total: %d\n", total);	
	}

	return 0;
}
Example #13
0
/*
 * Execute the specified command either by forking and executing
 * the program ourself, or else by using the shell.
 */
static void
runCmd(const char * cmd)
{
	const char *	cp;
	BOOL		magic;
	pid_t		pid;
	int		status;
	
	/*
	 * Check the command for any magic shell characters
	 * except for quoting.
	 */
	magic = FALSE;
	
	for (cp = cmd; *cp; cp++)
	{
		if ((*cp >= 'a') && (*cp <= 'z'))
			continue;
		
		if ((*cp >= 'A') && (*cp <= 'Z'))
			continue;
		
		if (isDecimal(*cp))
			continue;
		
		if (isBlank(*cp))
			continue;
		
		if ((*cp == '.') || (*cp == '/') || (*cp == '-') ||
			(*cp == '+') || (*cp == '=') || (*cp == '_') ||
			(*cp == ':') || (*cp == ',') || (*cp == '\'') ||
			(*cp == '"'))
		{
			continue;
		}
		
		magic = TRUE;
	}
	
	/*
	 * If there were any magic characters used then run the
	 * command using the shell.
	 */
	if (magic)
	{
		system(cmd);
		
		return;
	}
	
	/*
	 * No magic characters were in the command, so we can do the fork
	 * and exec ourself.
	 */
	pid = fork();
	
	if (pid < 0)
	{
		perror("fork failed");
		
		return;
	}
	
	/*
	 * If we are the child process, then go execute the program.
	 */
	if (pid == 0)
		childProcess(cmd);
	
	/*
	 * We are the parent process.
	 * Wait for the child to complete.
	 */
	status = 0;
	intCrlf = FALSE;
	
	while (((pid = waitpid(pid, &status, 0)) < 0) && (errno == EINTR))
		;
	
	intCrlf = TRUE;
	
	if (pid < 0)
	{
		fprintf(stderr, "Error from waitpid: %s", strerror(errno));
		
		return;
	}
	
	if (WIFSIGNALED(status))
	{
		fprintf(stderr, "pid %ld: killed by signal %d\n",
				(long) pid, WTERMSIG(status));
	}
}