c - linux execvp ; ls cannot access |, No such file or directory -
i trying code shell. shell doesn't execute command - ls -l | less. using execvp. code given below.
#include <stdio.h> #include <unistd.h> #include <string.h> int main(){ int pid, status, num, len; char str[1000], cwd[100]; char* word[100]; getcwd(cwd, sizeof(cwd)); while(1){ chdir(cwd); printf("%s > ", cwd); gets(str); pid=vfork(); if(pid == 0){ num = 0; word[num] = strtok (str, " "); while (word[num] != null) { word[num] = strdup (word[num]); len = strlen (word[num]); if (strlen (word[num]) > 0) if (word[num][len-1] == '\n') word[num][len-1] = '\0'; word[++num] = strtok (null, " "); } if(strcmp(word[0], "cd") == 0){ chdir(word[1]); getcwd(cwd, sizeof(cwd)); } else{ execvp(word[0],word); } exit(0); } else{ wait(&status); } } return 0; }
ls -l | less
shell command line consists of 2 processes connected pipe. execvp()
call can spawn single process.
if want program, must invoke shell explicitly - either using system()
call, or changing command line sh -c 'ls -l | less'
. word
array should this:
word[0] = "sh" word[1] = "-c" word[2] = "ls -l | less" word[3] = null
[edit] alternatively, shell doing internally: spawn 2 processes , connect them pipe. involve using fork()
, pipe()
, dup2()
, execve()
calls. however, invoking shell less work, , since less
interactive program anyway, don't need worry performance much: takes less 100 ms perceived instantaneous.
Comments
Post a Comment