简体   繁体   English

如何使用exec()系列实现shell命令cp和rm?

[英]How to use exec() family to implement the shell commands cp and rm?

how can I implement cp and rm shell commands using exec() family system calls ? 如何使用exec()系列调用实现cp和rm shell命令? I've searched a lot but did'nt find any helpful site/link ,can someone help please ??? 我搜索了很多,但没有找到任何有用的网站/链接,有人可以帮助吗???

Here's are examples. 这是一些例子。

The exec functions with l in their name take the list of arguments as their own arguments. 名称中带有lexec函数将参数列表作为自己的参数。 The p suffix means that the command should be found using $PATH , so you can just supply the command name. p后缀表示应该使用$PATH找到该命令,因此您只需提供命令名称即可。

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

The variants with v take the argument in a single array argument ("v" stands for vector ). 带有v的变量将参数置于单个数组参数中(“v”代表vector )。 In this case, I didn't use the e suffix, so I gave the full path to the program. 在这种情况下,我没有使用e后缀,所以我给出了该程序的完整路径。

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

In both cases, the first argument is also the name of the program, since this will become argv[0] in the new process. 在这两种情况下,第一个参数也是程序的名称,因为这将在新进程中变为argv[0] 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. 您应该在使用l变量时显式提供类型转换,因为varargs函数不会对指针进行自动类型转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM