• [^] # Re: je ne sais pas si j'ai bien saisi ton problème, mais bon ....

    Posté par . En réponse au message comment realiser une GUI ?. Évalué à 3.

    jaguarwan@Jaguar:~$ cat coincoin.c

    #include <stdlib.h> /* la libc ! */
    #include <stdio.h> /* printf(), fgets() */
    #include <unistd.h> /* read(), write(), xxx_FILENO */
    #include <string.h> /* memset() */
    #include <sys/types.h> /* pid_t */
    #include <sys/wait.h> /* wait() */


    #define PIPE_R 0 /* l'entree du pipe (input) c'est zero */
    #define PIPE_W 1 /* et le sortie c'est 1 */

    int main(int argc, char **argv)
    {
    pid_t fiston;
    int in[2];
    int out[2];
    char buffer[BUFSIZ];

    memset(buffer, 0, sizeof(buffer));

    /* on prepare les pipes */
    if (pipe(in) == -1) {
    perror("coincoin::pipe()");
    exit(EXIT_FAILURE);
    }

    if (pipe(out) == -1) {
    perror("coincoin::pipe()");
    exit(EXIT_FAILURE);
    }

    fiston = fork();

    /* mode papa */
    switch(fiston) {
    case -1:
    /* Oops. on a un probleme. */
    perror("Papa::fork()");
    exit(EXIT_FAILURE);
    break;

    case 0:
    /* ca a marche et on est dans le fiston.
    on redirige son stdin et son stdout sur les pipe. */

    printf("fiston est ne !\n");

    if (dup2(in[PIPE_R], STDIN_FILENO) == -1) {
    perror("Fiston::dup2()");
    exit(EXIT_FAILURE);
    }

    if (dup2(out[PIPE_W], STDOUT_FILENO) == -1) {
    perror("Fiston::dup2()");
    exit(EXIT_FAILURE);
    }

    setbuf(stdout, NULL); setbuf(stdin, NULL);

    /* ici on pourrait faire un execve pepere, ca conserve les descripteurs */

    /* si on fait pas de setbuf(), il faut des \n (ou des fflush()) */
    printf("plop ! plop !"); sleep(1);
    printf("gruiiiiiik"); sleep(1);
    printf("coincoin ?!");

    /* on attend une reponse du papa avant de mourir */
    fgets(buffer, sizeof(buffer), stdin);
    fprintf(stderr, "papa a repondu: %s **argh**\n", buffer);
    exit(EXIT_SUCCESS);
    break;

    default:
    /* ca a marche et on est dans le papa. */
    printf("papa est la.\n");

    /* on ecoute les idioties du fiston */
    for (int i = 0; i <= 2; i ++) {
    read(out[PIPE_R], buffer, sizeof(buffer));
    printf("(%i) le fiston dit: %s\n", i, buffer);
    memset(buffer, 0, sizeof(buffer));
    }

    /* on envoie un message au fiston */
    write(in[PIPE_W], "pan ! pan !\n", strlen("pan ! pan !\n"));
    /* (il faut *obligatoirement* un \n ici a cause du fgets de l'autre cote) */

    /* on attend qu'il creve */
    wait(NULL);
    }

    exit(EXIT_SUCCESS);
    }

    jaguarwan@Jaguar:~$ gcc -std=c99 -posix -pedantic -Wall coincoin.c
    jaguarwan@Jaguar:~$ ./a.out
    fiston est ne !
    papa est la.
    (0) le fiston dit: plop ! plop !
    (1) le fiston dit: gruiiiiiik
    (2) le fiston dit: coincoin ?!
    papa a repondu: pan ! pan !
    **argh**
    jaguarwan@Jaguar:~$