execv в .c prog, которые работают с одним и тем же каналом - PullRequest
0 голосов
/ 20 апреля 2019

Мне нужно написать код для запуска 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;
}

1 Ответ

1 голос
/ 21 апреля 2019

Из 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.

Примечание: Оба вызова являются вызовами библиотеки, предоставляемыми стандартнымС библиотека.Единственный системный вызов «семейства exec» - это execve ().

...