c - Using Fork for Command Line Arguements -
i'm trying execute command "ls -l" i'm not sure how approach it.
this i've tried:
int main(void) { char * input; char * args[2]; char buff[100]; input = malloc(sizeof(buff)); while(fgets(input,sizeof(input),stdin) != null) { printf("enter command\n"); if(strcmp(input,"ls -l\n") ==0) { pid_t childpid; childpid = fork(); if(childpid == 0) { args[0] = "/bin/ls -l"; args[1] = null; execv(args[0],args); } } } free(input); }
however, command doesn't seem work here. works if use "ls" want use "ls -l" there argument have pass work?
first have understand simple example.
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> int main() { /* status of child execution */ int status; /* pointer * array of char*(strings)*/ char ** args; /* allocate memory 3 char*(stings) */ args = (char**) malloc( 3 * sizeof(char*) ); /* fork program , store each fork id */ pid_t childpid = fork(); /* if child process */ if(childpid == 0) { args[0] = "ls"; args[1] = "-l"; args[2] = null; /* execute args[0] command args arguments */ execvp(args[0],args); /* send execution code 0 parent , terminate child */ exit(0); } else { /* wait execution code child*/ wait(&status); /* free allocated space */ free(input); free(args); /* exit program received code child */ exit(status); } }
i commented every line, tell me if want more informations. have understand how execute commands child , inform parent before continue user's input commands.
Comments
Post a Comment