fork() and exec() functions in C -
so writing program repeatedly reads lines of input standard input, splits them in char **array. each line, treat first element full path program executed. execute program, passing rest of items on line arguments. if line empty, nothing , go next line. repeat until first element string ”exit”.
my problems are:
- when input "exit", strcmp(l[0], "exit") returns 10 instead of 0. why?
- the program got compiled works odd number of arguments. example, if input "/bin/echo good", prints "this good" if input "/bin/echo good", prints "error".
here code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #define bufsize 10000 int space; char** createarray(char *line) { int len_line = strlen(line); char **wordarray = null; if(len_line > 1){ char *token = strtok(line, " "); space = 0; while (token) { wordarray = realloc(wordarray, sizeof(char*)*++space); wordarray[space-1] = token; token = strtok(null, " "); } } return wordarray; } int main(int argc, const char* argv[]) { char line[bufsize]; while (1) { printf("%s\n", ">"); fgets(line, bufsize, stdin); char** l = createarray(line); if (l) { /*why instaed of zero, when l[0] /*equals quit, strcmp() returns 10?*/ printf("%d\n", strcmp(l[0], "exit")); if(strcmp(l[0], "exit")==10) { exit(0); } else if(fork() == 0) { execv(l[0], l); printf("%s\n", "error!"); } } } return 1; }
coming first issue facing
1. when input "exit", strcmp(l[0], "exit") returns 10 instead of 0. why?
when type "exit" , press enter key, string read fgets "exit\n". comparing "exit" "exit\n" gives 10. either remove "\n" end before comparing or change comparison method
if(strcmp(l[0], "exit\n") == 0)
see corrected code below
int main(int argc, const char* argv[]) { char line[bufsize]; while (1) { printf("%s\n", ">"); fgets(line, bufsize, stdin); int len = strlen(line); line[len - 1] = 0; char** l = createarray(line); if (l) { /*why instaed of zero, when l[0] equals quit, strcmp() returns 10?*/ printf("%d\n", strcmp(l[0], "exit")); if(strcmp(l[0], "exit")==0) { exit(0); } else if(fork() == 0) { execv(l[0], l); printf("%s\n", "error!"); } } } return 1; }
regarding second issue
2. program got compiled works odd number of arguments. example, if input "/bin/echo good", prints "this good" if input "/bin/echo good", prints "error".
try corrected code given below. works. issue doesn't exist anymore.
Comments
Post a Comment