Hi, there. I have a small assignment: to make a little command line shell that executes programs. The shell is ok. My problem is to run processes. The code has to be 100% POSIX compatible.
So I thought using execv(...)
I've been reading the FAQs but don't understand well how to spawn the process. The shell is running then executes the progm. While the program is running the shell must remain idle. When the program ends, the shell must return. Could you please explain a bit better you execv works?? It seems that it spawns a process independent from the parent, but I'd like the parent to remain idle.
//EDIT:
I've been reading a bit more, and I found that calling system is the same as calling fork(), execv(), and wait(). But calling fork() always returns -1. Does this happens because I'm using windows??
Code:
#include<limits.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#define CMDSZ 512
#define N_TOKENS 64
int main(){
char cmd[CMDSZ];
char *tkns[N_TOKENS+1];
char curr_dir[PATH_MAX];
int curr_dir_len;
int i, k,len;
int pid;
getcwd(curr_dir,PATH_MAX);
curr_dir_len = strlen(curr_dir);
if(curr_dir[curr_dir_len-1]!='/'){
curr_dir[curr_dir_len++]='/';
curr_dir[curr_dir_len]=0;
}
while(1){
printf("minish > ");
fgets(cmd,CMDSZ,stdin);
tkns[0]=strchr(cmd,'\n');
if(tkns[0]) *(tkns[0])=0;
len = strlen(cmd);
k=i=0;
while(i<len && k<N_TOKENS){
if(cmd[i]==' '){
cmd[i++]=0;
while(cmd[i]==' ') i++;
}else if(cmd[i]=='\"'){
i++;
tkns[k++]=cmd+i;
while(cmd[i]!='\"') i++;
cmd[i++]=0;
}else{
tkns[k++]=cmd+i;
while(cmd[i]!=' ') i++;
cmd[i++]=0;
}
}
tkns[k]=0;
if(stricmp(tkns[0] , "quit")==0){
printf("mini-shell over.\n");
break;
}
pid = fork();
if(pid<0){
fprintf(stderr,"fork() error.\n");
getchar();
}else if(pid==0){
strcat(curr_dir+curr_dir_len,tkns[0]);
if(execv(curr_dir,tkns)<0)
printf("Error executing '%s'\n",tkns[0]);
}else
wait();
curr_dir[curr_dir_len]=0;
}
}