gpt4 book ai didi

c - execv 到 .c prog 使用相同的管道

转载 作者:行者123 更新时间:2023-11-30 14:39:59 24 4
gpt4 key购买 nike

我必须编写一个运行 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;
}

child

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”添加到路径中。

注意:这两个调用都是标准 C 库提供的库调用。 “exec 系列”的唯一系统调用是 execve()。

关于c - execv 到 .c prog 使用相同的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55777271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com