So basically my fork code is running really wack. I am sure the problem is something simple, I just can't see it. For some reason my fork() is not completing all the way. Like the first printf is not printing, yet the 2nd printf, which is commented; if I uncomment it, it prints the first and 2nd printf, but nothing after that seems to print for the child. The execv process also does not seem to run, even though it was running at one point.
#include <stdio.h>
#include<unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
char input[200];
char path[]="/bin/";
char str[80];
do{
printf("dash> ");
fgets(input, 200, stdin);
input[strcspn( input, "\n" )] = '\0';
char* token = strtok(input, " ");
// printf("TEST: %s",token);
strcpy(str, path);
strcat(str, token);
// printf("str1: %s", str);
int rc=fork();
if(rc<0){ // fork failed
printf("Error");
return 0;
}
else if(rc==0){//child process
printf("hello toekn is: %s ",token);
// printf("\nhello, I am child (pid:%d)\n", (int) getpid());
// char* arr[] = {"ls", NULL};
// printf("hello, I am child");
char *myargs[15];
myargs[0]=token;
int counter=0;
printf(token);
while(myargs[counter] != NULL){
counter++;
myargs[counter]=strtok(input, " ");
printf(myargs[counter]);
}
// myargs[1]=token;
myargs[counter+1]=NULL;
execv(str,myargs );
printf("failed");
}
else{ //parent process
int rc_wait=wait(NULL);
printf("hello, I am parent of %d (rc_wait:%d) (pid:%d)\n", rc, rc_wait,
(int) getpid());
// printf("\nHello %d", rc_wait);
}
}while(strcmp(input,"exit")!=0);
return 0;
}
So for example when the 2nd printf in the child is not commented this is the output:
dash> ls
hello toekn is: ls
hello, I am child (pid:33522)
hello, I am parent of 33522 (rc_wait:33522) (pid:33095)
dash>
And when it is commented :
dash> ls
hello, I am parent of 4017 (rc_wait:4017) (pid:3377)
dash>
As you can see for some reason, because the first printf is commented out the 2nd one also does not display. As well as the rest of the child process.
I feel like the problem is the child process does not complete in time, of the wait in parent. If anyone can help I would greatly appreciate it. Thanks
Using gcc (GCC) 4.8.5