Skip to content

C close() : Invalid argument

Sorry per advance for my english, i’m not english native and be indulgent i’m also a student.

I’m trying to recreate the pipe function in C, but i have a problem when i try to close pipe fd before the dup2(), the function close() return me an error ├Ćnvalid argument, i have already check if my fd is valid and created by pipe().

But now I don’t understand why my FD used as argument is not accepted by close() in my son process

After this on my parent process my function close() return me an undefined error

here is what the console returns to me when I run my program

close 1 2st cmd: Undefined error: 0

close 1 1st cmd: Invalid argument

pid_t       pid;
t_command   *cmd;
int         pipe_fd[2];

if (pipe(pipe_fd) == -1)

cmd = list->first;
if ((pid = fork()) == -1)
if (pid == 0)
    /* Code fils */
    cmd = cmd->next;
    if (!close(pipe_fd[1]))
        perror_exit("close 1 1st cmd");
    if (!dup2(pipe_fd[0], STDIN_FILENO))
        perror_exit("dup2 1st cmd");
    if (!close(pipe_fd[0]))
        perror_exit("close 2 1st cmd");
    if (!execve(cmd->path_exec, cmd->tab_cmd, envp))
        perror_exit("execve 1st cmd");
/* Code parent */
//waitpid(pid, NULL, 0);
if (!close(pipe_fd[0]))
    perror_exit("close 1 2st cmd");
if (!dup2(pipe_fd[1], STDOUT_FILENO))
    perror_exit("dup2 2st cmd");
if (!close(pipe_fd[1]))
    perror_exit("close 2 2st cmd");
if (!execve(cmd->path_exec, cmd->tab_cmd, envp))
    perror_exit("execve 2st cmd");



From the close manual

Return Value

close() returns zero on success. On error, -1 is returned, and errno is set appropriately.

That means you are checking for the wrong error condition. Should be:

if (close(pipe_fd[1]) == -1)

Same for the other close, dup2 and execve calls.

User contributions licensed under: CC BY-SA
1 People found this is helpful