使用execlp实现cp
时间: 2024-01-28 12:02:42 浏览: 18
把源文件复制到目标文件,可以使用execlp函数来实现:
```c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage: %s <source> <destination>\n", argv[0]);
return 1;
}
if (execlp("cp", "cp", argv[1], argv[2], NULL) == -1) {
perror("execlp");
return 1;
}
return 0;
}
```
在这个例子中,我们检查了命令行参数的数量,并使用execlp函数调用系统命令cp来复制源文件到目标文件。如果execlp函数返回-1,则表示调用失败,我们使用perror函数打印错误信息。
相关问题
execlp函数实现 ls -l -a 功能
可以使用 `execlp` 函数通过系统调用来执行 `ls -l -a` 命令,具体实现如下:
```c
#include <unistd.h>
int main()
{
execlp("ls", "ls", "-l", "-a", NULL);
return 0;
}
```
`execlp` 函数的第一个参数是要执行的程序名,第二个参数是程序名,第三个参数开始是程序的参数列表,参数列表必须以 NULL 结尾。在上面的例子中,我们传递了 `ls`、`-l` 和 `-a` 三个参数给 `ls` 命令,因此程序会执行 `ls -l -a` 命令。
需要注意的是,`execlp` 函数会取代当前进程,因此在执行完 `execlp` 后的代码不会被执行。如果 `execlp` 返回值为负数,则说明执行出错了。
父子进程间通信, 实现ps aux | grep bash 使用execlp函数和dup2函数
父子进程间通信可以使用管道(pipe)来实现。具体步骤如下:
1. 创建一个管道,使用pipe函数。
2. 创建子进程,使用fork函数。
3. 在子进程中,使用dup2函数将标准输出重定向到管道的写端,关闭管道的读端。
4. 在子进程中,使用execlp函数执行grep bash命令。
5. 在父进程中,关闭管道的写端,使用dup2函数将标准输入重定向到管道的读端。
6. 在父进程中,使用execlp函数执行ps aux命令。
7. 等待子进程结束,使用wait函数。
具体实现代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int fd[2];
pid_t pid;
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(fd[0]); // 关闭管道的读端
dup2(fd[1], STDOUT_FILENO); // 将标准输出重定向到管道的写端
execlp("ps", "ps", "aux", NULL);
exit(EXIT_FAILURE);
} else { // 父进程
close(fd[1]); // 关闭管道的写端
dup2(fd[0], STDIN_FILENO); // 将标准输入重定向到管道的读端
execlp("grep", "grep", "bash", NULL);
wait(NULL); // 等待子进程结束
exit(EXIT_SUCCESS);
}
return 0;
}
```