• [^] # Re: .

    Posté par (site web personnel) . En réponse au message popen / pclose. Évalué à 3.

    En fait il y a deux solution à ce problème:

    #include <sys/types.h>
    #include <sys/wait.h>
    #include <unistd.h>
    #include <stdlib.h>

    main () {

    int status, old_stdout, old_stderr, c;
    int pipe_stdout[2], pipe_stderr[2];
    char buffer[1024];

    /* creation pipes de communication */
    pipe(pipe_stdout);
    pipe(pipe_stderr);

    #if 1
    if (fork()) {
    close (pipe_stdout[0]);
    close (pipe_stderr[0]);
    /* redirect to pipe */
    dup2(pipe_stdout[1], STDOUT_FILENO);
    dup2(pipe_stderr[1], STDERR_FILENO);
    execl("/bin/ls", "ls", "-la", "/bin", (char*)NULL);
    }

    wait(NULL);
    #else
    /* Backup old i/o */
    dup2(STDOUT_FILENO, old_stdout);
    dup2(STDERR_FILENO, old_stderr);

    dup2(pipe_stdout[1], STDOUT_FILENO);
    dup2(pipe_stderr[1], STDERR_FILENO);
    system("/bin/ls -la --color /bin");

    /* restore old i/o */
    dup2 (old_stdout, STDOUT_FILENO);
    dup2 (old_stderr, STDERR_FILENO);
    #endif

    /* close (pipe_stdout[1]);
    close (pipe_stderr[1]);*/

    memset(buffer, 0, 1024);
    /* Lecture pipes */
    printf("Lecture stdout:\n");
    while (c=read(pipe_stdout[0], buffer, 1024)>0) {
    printf("%s", buffer);
    memset(buffer, 0, 1024);
    }

    memset(buffer, 0, 1024);
    printf("Lecture stderr:\n");
    while (c=read(pipe_stderr[0], buffer, 1024)>0) {
    printf("%s", buffer);
    memset(buffer, 0, 1024);
    }
    }