如何使用exec()系列实现Shell命令cp和rm? [英] How to use exec() family to implement the shell commands cp and rm?

查看:95
本文介绍了如何使用exec()系列实现Shell命令cp和rm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用exec()系列系统调用实现cp和rm shell命令?我已经搜索了很多,但是没有找到任何有用的网站/链接,有人可以帮忙吗?

how can I implement cp and rm shell commands using exec() family system calls ? I've searched a lot but did'nt find any helpful site/link ,can someone help please ???

推荐答案

以下是示例.

名称中带有lexec函数将参数列表作为自己的参数. p后缀意味着应该使用$PATH找到该命令,因此您只需提供命令名称即可.

The exec functions with l in their name take the list of arguments as their own arguments. The p suffix means that the command should be found using $PATH, so you can just supply the command name.

execlp("cp", "cp", "sourcefile", "destfile", (char *)0);

带有v的变体在单个数组参数中接受参数("v"代表vector).在这种情况下,我没有使用e后缀,所以我给出了程序的完整路径.

The variants with v take the argument in a single array argument ("v" stands for vector). In this case, I didn't use the e suffix, so I gave the full path to the program.

char *args[] = {"rm", "file1", "file2", 0);
execv("/bin/rm", args);

在两种情况下,第一个参数也是程序的名称,因为在新进程中,该名称将变为argv[0].参数的末尾用空指针表示.使用l变体时,您应该显式提供类型转换,因为varargs函数不会自动将类型转换为指针.

In both cases, the first argument is also the name of the program, since this will become argv[0] in the new process. And the end of arguments is signified with a null pointer. You should provide the typecast explicitly when using the l variants, since varargs functions don't do automatic type conversion to pointers.

这篇关于如何使用exec()系列实现Shell命令cp和rm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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