c - 如何将 execv 用于 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[] 参数是一个指向以 null 结尾的字符串的指针数组,这些字符串表示新程序可用的参数列表。按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。指针数组必须以空指针终止。
你需要改变
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 );
推荐阅读
- python - 使用列表的 Python 登录系统
- javascript - JavaScript DIV 编辑会破坏其他元素的功能
- sql - 在 laravel 上使用多个连接参数构建查询
- excel - Excel粘贴到PPT后定位表出现问题
- c++ - 转动 shared_ptr
参考 - c# - 第三人称角色移动的问题
- javascript - 浏览器同步 webpack 插件不工作
- javascript - 检测是否启用了 webgl 硬件加速
- typescript - 如何使打字稿推断出更具体的类属性类型?
- java - spring cloud config在379:64处抛出Bad Base64输入字符