2013-10-20 98 views
0

我有一个任务来编写一个c程序,该程序可以使用fork和exec在$ PATH中列出的所有目录中搜索目录。我的问题是我如何得到的方式,然后我就可以在我的代码中使用它与EXECL

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <sys/wait.h> 

int main(int argc, char* argv[]) { 
    int pid = 0; 
    for(int i = 0; i < argc; i++) { 
    if (pid = fork() != 0){ 
     printf("Arg%d: %c\n", i, *argv[i]); // replace with exec ls -l <dir>/<arg> 
     return 0; 
    } 
    } 

    return 0; 
} 
+4

With ['getenv()'](http://en.cppreference.com/w/c/program/getenv)? –

+1

请记住,'argv [0]'是* your *程序的名称。 –

+0

@JOACHIMPILEBORG你是对的,我错过了。 –

回答

3

你可以使用getenv()(男子3 GETENV)PATH环境变量从$ PATH路径。将该字符串复制到char*中,然后使用':'作为分隔符将其与strtok()(man 3 strtok)分开。您应该将原始字符串复制到新的char*中,因为您从getenv()获得的指针实际上指向环境内部,并且strtok()将修改您传递给它的参数。然后您可以为每个子字符串分叉一个循环。

+0

谢谢,它工作。 –