unix路径搜索C函数 [英] unix path searching C function

查看:79
本文介绍了unix路径搜索C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 UNIX shell,我必须使用 execv() 系统调用来创建一个进程.execv() 的参数之一是可执行文件的文件路径.因此,如果有人输入 /bin/ls,它将运行 ls 可执行文件.但我需要的是一个函数,当输入 ls 时,它会搜索 ls 的文件路径(就像 which 命令).有什么功能可以让我这样做吗?

I am programming a UNIX shell and I have to use the execv() system call to create a process. One of the parameters for execv() is the filepath for the executable. So if somebody types in /bin/ls, it will run the ls executable. But what I need is a function such that when ls is typed, it will search for the filepath of ls (like the which command). Is there a function which allows me to do that?

不幸的是,这是一个学校项目,我不允许使用 execvp().我需要实现一些路径搜索功能,然后将该文件路径添加到 execv() 参数.

Unfortunately, this is a school project an I am not allowed to use execvp(). I need to implement some path searching function and then addon that filepath to the execv() parameter.

推荐答案

使用 PATH = getenv("PATH") 从环境中获取路径字符串,然后使用对 的连续调用strtok(PATH,":") 然后 strtok(NULL,":")PATH 字符串中的路径解析为 char **path,您需要使用 malloc() 分配.将 path[x] + '/' + argv[0] 放入缓冲区,并使用 access(buffer, X_OK) 查看是否可以在该路径位置执行您的文件,如果可以,请执行您的 execv(buffer,argv).

Use PATH = getenv("PATH") to get the path string from the environment, then use successive calls to strtok(PATH,":") then strtok(NULL,":") to parse out the paths from the PATH string into an array of char **path, which you will need to allocate with malloc(). Place path[x] + '/' + argv[0] into a buffer, and use access(buffer, X_OK) to see if you can execute your file at that path location, if so, perform your execv(buffer,argv).

这篇关于unix路径搜索C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆