hey guys,
im have written a code that all it does is get user input and run a simple fork task.
the problem i am running is the commands i type for example /bin/ls and so on does nothin it jsut asks for the next input.
Could someone give me a hint as to what i should look at.
this is written in linux, using POSIX.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>


#define MAXBUFFER	255
#define MaxBUFFERMEM	255
#define INPUTLEN	255
#define SHELL		"$> "
#define TRUE		1

init_params(char* parameters[]){
	int i;
	for (i=0;i<MAXBUFFER; i++){
		parameters[i]=NULL;
	}
}

void type_command(){
	printf("%s",SHELL);

}


void read_command(char* command, char* parameters[]){
	char c;
	char tmp[MAXBUFFER];
	int i=0;
	c=getchar();
	char* sub_string;
	char cmd[10];
	do{
		while(c!='\n'){
			tmp[i]=c;
			i++;
			c=getchar();
		}
		tmp[i]='\0';
	}while(strlen(tmp)==0);
	strncpy(command,strtok(tmp," "),50);
//	printf("First: %s\n", strtok(tmp," "));
	while ( (sub_string=strtok(NULL," "))!=NULL){
		parameters[i]=malloc(MAXBUFFER);
		strncpy(parameters[i],sub_string,50);
		i++;
	}
}




int main(){
	char command[100];
	char* parameters[100];
	int status;
	while(TRUE){				/*repeat forever*/
	type_command();			/*display prompt on the screen*/
	init_params(parameters);
	read_command(command,parameters);	/*read input from terminal*/
	if(fork()!=0){				/*fork off child process*/
		/*Parent code.*/
		waitpid(-1,&status,0);		/*wait for child to exit*/
		}
	else{
		/*child code.*/
		execve(command,parameters,0);	/*execute command*/
		if (errno!=0){
			fprintf(stderr, errno);
		}
	}
	return 0;
}

thanks in advance

hi,

When i execute this code it keep on asking the input...
how to come out?
what is the action of fork process here?

fork make copies of same program. So every time it asking for input. Use a flag variable to take in put:

int main(){
	char command[100];
	char* parameters[100];
	int status;
                int input_flag = 0;
	while(TRUE){				/*repeat forever*/
	type_command();			/*display prompt on the screen*/
	init_params(parameters);
                if(input_flag==0)
	      read_command(command,parameters);	/*read input from terminal*/
	if(fork()!=0){				/*fork off child process*/
		/*Parent code.*/
		waitpid(-1,&status,0);		/*wait for child to exit*/
                                 input_flag=1;

		}
                     	else{
		/*child code.*/
		execve(command,parameters,0);	/*execute command*/
		if (errno!=0){
			fprintf(stderr, errno);
		}
	}
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.