6、execvp函数的应用,要在程序中执行命令ps -ef,命令ps在“/bin”目录下。在这一函数中,参数v为构造指针数组,参数p为文件查找方式(不需要给出路径)。因而构造的指针数组为char *arg[]={“ps”,”-ef”,NULL};此函数的调用形式为execvp(“ps”,arg);请编写一程序进行调试。
时间: 2024-02-15 12:04:39 浏览: 35
下面是一个简单的程序,可以调用execvp函数执行ps -ef命令:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
char *arg[] = {"ps", "-ef", NULL};
execvp("ps", arg);
return 0;
}
```
在这个程序中,我们首先定义了一个指针数组arg,用于存储要执行的命令及其参数。然后,我们调用execvp函数,将“ps”作为第一个参数,arg作为第二个参数,以执行ps -ef命令。
需要注意的是,如果execvp函数执行成功,那么程序将不会继续执行下去,因为当前进程的代码和数据都会被新的命令所替换。如果需要在执行完命令后,继续执行原来的程序,可以在一个子进程中调用execvp函数。
相关问题
使用execl()函数,在子进程内运行ps -ef命令。 (2)使用exec函数族中的其它5个函数,实现同样的功能。
1. 使用execl()函数,在子进程内运行ps -ef命令:
```c
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
pid = fork();
if (pid == 0) {
execl("/bin/ps", "ps", "-ef", NULL);
printf("exec error!\n");
}
return 0;
}
```
2. 使用exec函数族中的其它5个函数,实现同样的功能:
```c
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
char *const args[] = {"ps", "-ef", NULL};
pid = fork();
if (pid == 0) {
execv("/bin/ps", args);
printf("exec error!\n");
}
return 0;
}
```
```c
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
char *const args[] = {"ps", "-ef", NULL};
char *const envp[] = {NULL};
pid = fork();
if (pid == 0) {
execve("/bin/ps", args, envp);
printf("exec error!\n");
}
return 0;
}
```
```c
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
char *const args[] = {"ps", "-ef", NULL};
pid = fork();
if (pid == 0) {
execvp("ps", args);
printf("exec error!\n");
}
return 0;
}
```
```c
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
char *const args[] = {"ps", "-ef", NULL};
char *const envp[] = {NULL};
pid = fork();
if (pid == 0) {
execvpe("ps", args, envp);
printf("exec error!\n");
}
return 0;
}
```
如何让子进程执行ps-a命令
要让子进程执行"ps -a"命令,可以使用fork函数创建一个新的进程,并在子进程中调用exec系列函数执行"ps -a"命令。
首先,使用fork函数创建一个新的子进程,该函数会复制父进程的所有内容给子进程,包括代码、数据、文件描述符等。子进程会继承父进程的环境。
接下来,通过调用exec系列函数在子进程中执行命令。exec函数会将子进程的地址空间替换为新的可执行文件并执行它。ps命令通常在/bin目录下,可以使用execvp函数来执行。
下面是示例代码:
```c++
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork(); // 创建子进程
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(1);
} else if (pid == 0) {
// 子进程中
char* args[] = {"ps", "-a", NULL}; // 命令行参数
execvp("ps", args); // 执行ps命令
exit(1); // 如果执行失败,则子进程退出
} else {
// 父进程中
wait(NULL); // 等待子进程结束
}
return 0;
}
```
在这个示例中,父进程使用fork函数创建一个新的子进程,在子进程中利用execvp函数执行"ps -a"命令。父进程则等待子进程结束,然后程序结束。
执行以上代码,子进程会执行"ps -a"命令,并输出进程的信息。
注意,由于exec函数会取代子进程的地址空间,所以子进程的逻辑需要在exec函数之前定义,exec函数后面的代码不会被执行。