繁体   English   中英

execv到.c prog,可在同一管道中使用

[英]execv to .c prog that work with the same pipe

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM