c - execv 到 .c prog 使用相同的管道
问题描述
我必须编写一个运行 fork 的代码。孩子是另一个必须完成的主要项目。我运行该execv()
功能,但找不到路径。子文件在同一台计算机的其他项目中。
第二个问题:这child
是我的程序。如何使其可执行?
int main(int argc, char **argv)
{
int pipefd[2];
pid_t cpid1;
char *checkRows[] = { "child", "-r", NULL };
if (pipe(pipefd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
cpid1 = fork();
if (cpid1 == 0)
{ // child 1
printf("after fork %d", cpid1);
dup2(pipefd[1], 1); // redirect stdout to pipe
close(pipefd[0]);
execv("child",checkRows);
perror("execc rows failed");
}
else if (cpid1 == -1)
{ // fork failed
printf("error!");
exit(EXIT_FAILURE);
}
close(pipefd[1]);
return EXIT_SUCCESS;
}
孩子
int main(int argc, char **argv)
{
if (argc != 3){
printf("there is no arguments pass");
exit(EXIT_FAILURE);
}
printf("In child");
return 0;
}
解决方案
来自 execv(3):
int
execv(const char *path, char *const argv[]);
The execv(), execvp(), and execvP() functions provide an array of point-
ers to null-terminated strings that represent the argument list available
to the new program. The first argument, by convention, should point to
the file name associated with the file being executed. The array of
pointers must be terminated by a NULL pointer.
从 execvp(3) (实际上是相同的手册页):
int
execvp(const char *file, char *const argv[]);
The functions execlp(), execvp(), and execvP() will duplicate the actions
of the shell in searching for an executable file if the specified file
name does not contain a slash ``/'' character. For execlp() and
execvp(), search path is the path specified in the environment by
``PATH'' variable. If this variable isn't specified, the default path is
set according to the _PATH_DEFPATH definition in <paths.h>, which is set
to ``/usr/bin:/bin''. For execvP(), the search path is specified as an
argument to the function. In addition, certain errors are treated spe-
cially.
这意味着您可以使用
execv("/absolute/patch/to/child",...)
作为替代解决方案,您可以使用
execvp("child",...)
将“/absolute/patch/to”添加到 PATH 中。
注意:这两个调用都是标准 C 库提供的库调用。“exec 系列”的唯一系统调用是 execve()。
推荐阅读
- c# - 我应该使用设计模式将抽象基类中的逻辑放在其他地方吗?
- ios - midi 数据包列表不会更改时间戳
- javascript - laravel 和 react 上传文件返回 500 Internal Server Error
- java - 在 Java 8 Comparator 的 Sort 方法中切换 Sort filter 参数
- azure - 使用 terraform 输出恢复 Azure ARm 模板的输出值
- node.js - Mogoose:在更新文档之前检查架构中是否存在字段
- java - 使用 Lookback API - 查询错误:不完整的交集 - 发布范围更改
- java - 如何将 for 循环和 if 语句重新格式化为 java 8
- java - 如何在现有的 Observable 上发布新的 CompletableFuture 结果?
- plot - 创建数据分区图