![](/img/trans.png)
[英]How to combine `lshw` and `grep` command inside `execv` in C?
[英]How to use execv for grep?
我的 grep 在 /bin/usr/grep 中。 我的子进程确实运行,但它不执行execv
命令。 我在我的“ques29.c”文件中搜索“include”这个词,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid = fork();
if (pid < 0)
perror("Failed to fork.");
else if (pid == 0)
{
char *argv[] = { "-n", "include", "ques29.c", "NULL" };
execv("/usr/bin/grep", argv);
}
else
{
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
{
int exit_status = WEXITSTATUS(status);
printf("Parent: Process ID %ld Exit status of the child was %d\n", (long)getpid, exit_status);
}
}
return 0;
}
输出
Parent: Process ID 140735031147632 Exit status of the child was 0
v - execv(), execvp(), execvpe()
char *const argv[] 参数是一个指向空终止字符串的指针数组,这些字符串表示新程序可用的参数列表。 按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。 指针数组必须以空指针终止。
你需要改变
char *argv[] = { "-n", "include", "ques29.c", "NULL" };
execv("/usr/bin/grep", argv);
到
char *argv[] = { "/usr/bin/grep", "-n", "include", "ques29.c", NULL };
execv(argv[0], argv);
正如评论中所指出的,处理对exec*()
的失败调用可能应该完成:
execv(argv[0], argv);
// no need to check the return value as
// a successful call won't return
perror( "execv()" );
// note that return and exit() can cause
// problems with more complex code
_exit( 255 );
该数组需要由NULL
指针终止,但在您的代码中,最后一个元素是字符串文字"NULL"
,第一个参数必须是可执行文件的路径:
取而代之的是:
char *argv[] = { "-n", "include", "ques29.c", "NULL" };
你要这个:
char *argv[] = {"/usr/bin/grep", "-n", "include", "ques29.c", NULL };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.