c - execv waiting for input input instead of executing program -


i have program named "test" executes program called "hello". after receiving name of desired program, program seems wait more input in order display "hello" program code. snippet of example code

#include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> /* fork */ #include <sys/wait.h> /* wait */ int main()  {      char *temp[] = {null,null,null,null};     char  buf[bufsiz];     char s[256];      while(1) {          printf("type r @ next input\n");         fgets(buf, sizeof(buf), stdin);          strtok(buf, "\n");          if((strcmp(buf,"r")) == 0) { //if r typed             printf("run file : ");             scanf("%s ",s);              pid_t = fork();             if (i == 0) //we in child process             {                 execv(s,temp);                 _exit(1);             }             if (i != 0) { //parent                 wait(null);             }         }         else             exit(0);     } } 

the "hello" program is...

#include<stdio.h>  main(int argc, char* argv[]) {     printf("\nhello world\n");  } 

and example run shell on linux is...* means input, // comments

issac@issac-thinkpad-t440s ~$ ./a.out type r @ next input *r* run file : *hello* *r*    //i cant proceed unless type character input *r*?  hello world    //after ?additional? input displays "hello" program code type r @ next input    //loops program skips input? run file ex ? hello :  

i realize may simple mistake cant figure out whats wrong this. realize last part skipped input due input buffer having newline in there more confusing why after executing "hello" program waits more input display result.

to answer first question: drop trailing whitespace in scanf() looks this: scanf("%s",s);.

to answer second question: problem mix scanf() , fgets(). newline not consumed scanf() , passed new input next (non-first) fgets. easiest solution use fgets in both places:

#include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> /* fork */ #include <sys/wait.h> /* wait */ #include <string.h>  int main()  {      char *temp[] = {null,null,null,null};     char  buf[bufsiz];     char s[256];      while(1) {         printf("type r @ next input\n");         fgets(buf, sizeof(buf), stdin);         strtok(buf, "\n");          if((strcmp(buf,"r")) == 0) { //if r typed             printf("run file : ");             fgets(s, sizeof(s), stdin);             strtok(s, "\n");             pid_t = fork();             if (i == 0) //we in child process                 {                     execv(s,temp);                     _exit(1);                 }             if (i != 0) { //parent                 wait(null);             }         }         else             exit(0);     } } 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -