IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C Discussion :

Gestion des signaux : SIGTSTP


Sujet :

C

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    153
    Détails du profil
    Informations personnelles :
    Âge : 36
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Avril 2009
    Messages : 153
    Points : 160
    Points
    160
    Par défaut Gestion des signaux : SIGTSTP
    Bonjour à tous,

    Pour "rigoler", je me suis mis en tête d'implémenter un Shell from scratch en me basant uniquement sur les fonctions de la lib standard.

    J'avance lentement, mais surement. Cependant, je rencontre actuellement un petit problème sur la gestion des signaux et plus particulièrement de SIGTSTP (^Z).

    Je vais détailler rapidement ma façon de procéder pour implémenter ce Shell puis je vous donnerai les morceaux de code qui me semblent les plus pertinents pour la résolution de ce problème. Si vous trouvez qu'il manque quelque chose, n'hésitez pas à demander.


    Voici donc le principe, je lance une boucle "infinie" et je lis l'entrée standard jusqu'à rencontrer une fin de ligne (sauf si on a ouvert des quotes ou que le dernier caractère est un '\' pour les commandes sur plusieurs lignes) et la place dans un char *. Je parse ensuite toute la chaîne de caractère pour la placer dans une structure que j'ai nommé input_line. Une input_line est une liste doublement chaînée servant à stocker des 'command'. Une input_line peut donc contenir plusieurs command (exemple : "ls | grep toto" => 2 commandes).
    J'exécute ensuite les commandes une à une.

    Voilà ce que j'arrive à faire aujourd'hui :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
     
    ziirish@carbon:~/workspace/shelldone/src$ valgrind ./shelldone
    ==8381== Memcheck, a memory error detector
    ==8381== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
    ==8381== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright
    info
    ==8381== Command: ./shelldone
    ==8381==
    ziirish@carbon:~/workspace/shelldone/src$ ./test/bl
    blah    blah.c
    ziirish@carbon:~/workspace/shelldone/src$ ./test/blah
    1
    2
    ^Z
    [1] 8384 (./test/blah) stopped
    ziirish@carbon:~/workspace/shelldone/src$ jobs
    [1]  + 8384 (./test/blah) running
    ziirish@carbon:~/workspace/shelldone/src$ ps aux | grep blah
    ziirish   8384  0.0  0.1   3712   428 pts/4    T+   10:21   0:00 ./test/blah
    ziirish  22437  0.0  0.0  25184    44 ?        Ss   May11   0:00 SCREEN -S blah
    ziirish@carbon:~/workspace/shelldone/src$ fg
    3
    [1]  continued 8384 (./test/blah)
    4
    5
    ^C
    ziirish@carbon:~/workspace/shelldone/src$ quit
    ==8381==
    ==8381== HEAP SUMMARY:
    ==8381==     in use at exit: 0 bytes in 0 blocks
    ==8381==   total heap usage: 6,713 allocs, 6,713 frees, 550,849 bytes allocated
    ==8381==
    ==8381== All heap blocks were freed -- no leaks are possible
    ==8381==
    ==8381== For counts of detected and suppressed errors, rerun with: -v
    ==8381== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
    Mon problème, c'est que la commande 'jobs' ne m'indique pas que le process est stoppé et ps le voit en T+ alors que dans les autres shell, il est simplement en T.

    Le code :

    Code c : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
     
    int
    main (int argc, char **argv)
    {
        /* initializing shelldone */
        shelldone_init ();
     
        /* infinite loop waiting for commands to launch */
        shelldone_loop ();
     
    /* avoid the 'unused variables' warning */
        (void) argc;
        (void) argv;
     
    /* we don't need to cleanup anything since we registered the cleanup function */
        return 0;
    }
     
    static void
    shelldone_init (void)
    {
        /* get the hostname */
        host = xmalloc (30);
        gethostname (host, 30);
        /* load the commands list */
        init_command_list ();
        /* load the history */
        init_history ();
        /* register the cleanup function */
        atexit (shelldone_clean);
        /* load jobs list */
        init_jobs ();
        /* ignoring SIGINT */
        struct sigaction sa;
        sa.sa_handler = handler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        if (sigaction (SIGINT, &sa, NULL) != 0)
            err (3, "sigaction");
        sa.sa_handler = SIG_IGN;
        if (sigaction (SIGTSTP, &sa, NULL) != 0)
            err (3, "sigaction");
    }
     
    /**
     * Signal handler for the signal 2 (SIGINT (^C))
     */
    static void
    handler (int sig)
    {
        (void) sig;
        interrupted = TRUE;
        if (!running)
            fprintf (stdout, "^C\n");
        else
            fprintf (stdout, "\n");
    }
     
    static void
    shelldone_loop (void)
    {   
        while (1)
        {
            signal (SIGTSTP, SIG_IGN);
            interrupted = FALSE;
            free_line (l);
            xfree (li);
            li = NULL;
            l = NULL;
            const char *pt = get_prompt ();
            list_jobs (FALSE);
            /* read the input line */
            li = read_line (pt);
            if (xstrcmp ("quit", li) == 0)
                break;
            if (xstrlen (li) > 0)
                insert_history (li);
            /* parsing the input line into a command-line structure */
            l = parse_line (li);
    /*        dump_line (l);*/
            /* execute the command-line */
            running = TRUE;
            run_line (l);
            running = FALSE;
        }
    }
     
    void
    run_line (input_line *ptr)
    {
        CmdFlag flag;
        int ret = 0;
        if (ptr != NULL)
        {   
            command_line *cmd = ptr->head;
            while (cmd != NULL)
            {   
                switch (cmd->content->flag)
                {   
                /*  
                 * launch a command in background is pretty much the same as
                 * launch it in forground except in one case we wait until it's
                 * done and in the other case we don't
                 */
                case BG: 
                case END:
                {   
                    pid_t p = run_command (cmd);
                    cmd->content->pid = p;
                    /* p should never be equal to -1 */
                    if (p != -1 && !cmd->content->builtin)
                    {
                        if (cmd->content->flag == BG)
                        {
                            ret_code = 0;
                            enqueue_job (cmd->content, FALSE);
                        }
                        else
                        {
                            waitpid (p, &ret, WUNTRACED);
                            ret_code = WEXITSTATUS(ret);
                        }
                    }
                    else if (p == -1)
                        ret_code = 254;
                    break;
                }
                case OR:
                case AND:
                {
                    int nb = 1, i;
                    pid_t p;
                    command_line *exec = cmd, *save;
                    flag = cmd->content->flag;
                    while (exec != NULL && exec->content->flag == flag)
                    {
                        nb++;
                        save = exec;
                        exec = exec->next;
                    }
                    if (exec != NULL)
                        save = exec;
                    exec = cmd;
                    p = run_command (exec);
                    exec->content->pid = p;
                    if (p != -1 && !exec->content->builtin)
                    {
                        waitpid (p, &ret, WUNTRACED);
                        ret_code = WEXITSTATUS(ret);
                    }
                    else if (p == -1)
                        ret_code = 254;
                    i = 1;
                    exec = exec->next;
                    while (i < nb && ((flag == AND) ?
                                            (ret_code == 0) :
                                            (ret_code != 0)))
                    {
                        p = run_command (exec);
                        exec->content->pid = p;
                        if (p != -1 && !exec->content->builtin)
                        {
                            waitpid (p, &ret, WUNTRACED);
                            ret_code = WEXITSTATUS(ret);
                        }
                        else if (p == -1)
                            ret_code = 254;
                        exec = exec->next;
                        i++;
                    }
                    cmd = save;
                    break;
                }
                case PIPE:
                {
                    int nb = 1, i, fd[2];
                    pid_t *p;
                    unsigned int *builtins;
                    command_line *exec = cmd, *save = cmd;
                    while (exec != NULL && exec->content->flag == PIPE)
                    {
                        nb++;
                        exec = exec->next;
                    }
                    p = xmalloc (nb * sizeof (pid_t));
                    builtins = xmalloc (nb * sizeof (unsigned int));
                    exec = cmd;
                    for (i = 0; i < nb; i++)
                    {
                        pipe (fd);
                        if (i != nb - 1)
                            exec->content->out = fd[1];
                        p[i] = run_command (exec);
                        builtins[i] = exec->content->builtin;
                        exec->content->pid = p[i];
                        if (exec->content->out != STDOUT_FILENO &&
                            exec->content->out != STDERR_FILENO)
                            close (exec->content->out);
                        if (exec->content->err != STDERR_FILENO &&
                            exec->content->err != STDOUT_FILENO)
                            close (exec->content->err);
                        save = exec;
                        exec = exec->next;
                        if (exec != NULL)
                            exec->content->in = fd[0];
                    }
                    for (i = 0; i < nb; i++)
                    {
                        if (p[i] != -1 && !builtins[i])
                        {
                            waitpid (p[i], &ret, WUNTRACED);
                            ret_code = WEXITSTATUS(ret);
                        }
                        else if (p[i] == -1)
                            ret_code = 254;
                    }
                    xfree (p);
                    xfree (builtins);
                    cmd = save;
                    break;
                }
                }
                cmd = cmd->next;
            }
        }
    /*    exit (ret_code);*/
    }
     
    pid_t
    run_command (command_line *ptrc)
    {
        if (ptrc == NULL)
            return -1;
        command *ptr = ptrc->content;
        curr = ptr;
        pid_t r = -1;
        if (ptr != NULL)
        {  
            size_t len = xstrlen (ptr->cmd);
            if (len >= 2 && ptr->cmd[len - 1] == 'h' && ptr->cmd[len - 2] == 's')
            {  
                if (!(len > 3 &&
                    ptr->cmd[len - 1] == 'h' &&
                    ptr->cmd[len - 2] == 's' &&
                    ptr->cmd[len - 3] == '.'))
                {  
                    fprintf (stdout,
                             "BAZINGA! I iz in ur term blocking ur Shell!\n");
                    ptr->builtin = TRUE;
                    return 0;
                }
            }
            cmd_builtin call = NULL;
            int i = 0;
            while (calls[i].key != NULL)
            {  
                if (xstrcmp (ptr->cmd, calls[i].key) == 0)
                {  
                    call = calls[i].func;
                    break;
                }
                i++;
            }
            if (call != NULL)
            {
                /**
                 * FIXME: little hack to avoid compilation warning
                 */
                for (i = 0; i < ptr->argc; i++)
                    if (check_wildcard_match (ptr->argv[i], "toto"))
                    {
    /*                        argv[i] = xstrdup (ptr->argv[i]); */;
                    }
                r = call (ptr->argc, ptr->argv, ptr->in, ptr->out, ptr->err);
                ret_code = r;
                ptr->builtin = TRUE;
            }
            else
            {
                signal (SIGTSTP, sigstophandler);
                r = fork ();
                if (r == 0)
                {
                    if (ptr->flag == BG)
                        signal (SIGTSTP, SIG_IGN);
                    else
                        signal (SIGTSTP, SIG_DFL);
                    if (ptr->in != STDIN_FILENO)
                    {
                        dup2 (ptr->in, STDIN_FILENO);
                    }
                    if (ptr->out != STDOUT_FILENO)
                    {
                        if (ptr->out == STDERR_FILENO)
                            dup2 (ptr->err, STDOUT_FILENO);
                        else
                            dup2 (ptr->out, STDOUT_FILENO);
                    }
                    if (ptr->err != STDERR_FILENO)
                    {
                        if (ptr->err == STDOUT_FILENO)
                            dup2 (ptr->out, STDERR_FILENO);
                        else
                            dup2 (ptr->err, STDERR_FILENO);
                    }
                    /* Here we add the argv[0] which is the program name */
                    char ** argv;
                    if (ptr->argc > 0)
                    {
                        int i;
                        argv = xcalloc (ptr->argc + 2, sizeof (char *));
                        argv[0] = ptr->cmd;
                        for (i = 1; i - 1 < ptr->argc; i++)
                        {
                            if (xstrcmp ("$?", ptr->argv[i-1]) == 0 &&
                                ptr->protected[i-1] != SINGLE_QUOTE)
                            {
                                char buf[128];
                                snprintf (buf, 128, "%d", ret_code);
                                argv[i] = buf;
                            }
                            else
                                argv[i] = ptr->argv[i-1];
                        }
                        argv[i] = NULL;
                    }
                    else
                        argv = (char *[]){ptr->cmd, NULL};
                    execvp (ptr->cmd, argv);
                    err (1, "%s", ptr->cmd);
                }
            }
        }
        return r;
    }
     
    command *curr;
     
    void
    sigstophandler (int sig)
    {
        fprintf (stdout, "\n");
        kill (curr->pid, SIGTSTP);
        enqueue_job (curr, TRUE);
        (void) sig;
    }
     
    void
    list_jobs (unsigned int print)
    {
        job *tmp = list->head;
        while (tmp != NULL)
        {   
            job *tmp2 = tmp->next;
            if (!is_job_done (tmp->content->pid) && print)
                fprintf (stdout, "[%d]  + %d (%s) running\n",
                                 tmp->content->job,
                                 tmp->content->pid,
                                 tmp->content->cmd);
            tmp = tmp2;
        }   
    }
     
    static unsigned int
    is_job_done (pid_t pid)
    {
        int status;
        pid_t p = waitpid (pid, &status, WNOHANG|WUNTRACED);
        if (p == -1)
        {
            int idx = index_of (pid);
            remove_job (idx);
            warn ("jobs");
            return TRUE;
        }
        if (p == 0)
            return FALSE;
        if (WIFSTOPPED(status) != 0)
        {
            int idx = index_of (pid);
            job *j = get_job (idx);
            fprintf (stdout, "[%d]  + %d (%s) stopped\n",
                             j->content->job,
                             pid,
                             j->content->cmd);
            /* well, it's a lie but we don't want to print it twice */
            return TRUE;
        }
        else if (WIFEXITED(status) != 0)
        {
            int idx = index_of (pid);
            job *j = get_job (idx);
            fprintf (stdout, "[%d]  + %d (%s) terminated with status code %d\n",
                             j->content->job,
                             pid,
                             j->content->cmd,
                             WEXITSTATUS(status));
            remove_job (idx);
            return TRUE;
        }
        else if (WIFSIGNALED(status) != 0)
        {
            int idx = index_of (pid);
            job *j = get_job (idx);
            int sig = WTERMSIG(status);
            fprintf (stdout, "[%d]  + %d (%s) interrupted by signal %d (%s)\n",
                             j->content->job,
                             pid,
                             j->content->cmd,
                             sig,
                             strsignal (sig));
            remove_job (idx);
            return TRUE;
        }
        return FALSE;
    }
     
    int
    sd_jobs (int argc, char **argv, int in, int out, int err)
    {
        (void) argc;
        (void) argv;
        (void) in; 
        (void) out;
        (void) err;
     
        list_jobs (TRUE);
     
        return 0;
    }
     
    int
    sd_fg (int argc, char **argv, int in, int out, int err)
    {
        (void) argc;
        (void) argv;
        (void) in;
        (void) out;
        (void) err;
     
        job *tmp = get_last_enqueued_job (TRUE);
        if (tmp != NULL)
        {
            int status;
            int r;
            kill (tmp->content->pid, SIGCONT);
            fprintf (stdout, "[%d]  continued %d (%s)\n",
                             tmp->content->job,
                             tmp->content->pid,
                             tmp->content->cmd);
            curr = tmp->content;
            signal (SIGTSTP, sigstophandler);
            r = waitpid (tmp->content->pid, &status, 0);
            if (r != -1)
                ret_code = WEXITSTATUS(status);
            else
                ret_code = 254;
            free_command (tmp->content);
            xfree (tmp);
        }
        else
        {
            fprintf (stderr, "fg: no jobs enqeued\n");
            ret_code = 254;
        }
     
        return ret_code;
    }

    Si vous aviez une idée du problème ou un exemple de code pour gérer le SIGTSTP ça m'intéresse grandement.

    Merci

  2. #2
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    153
    Détails du profil
    Informations personnelles :
    Âge : 36
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Avril 2009
    Messages : 153
    Points : 160
    Points
    160
    Par défaut
    Finalement j'ai triché en ajoutant un flag 'stopped' comme indiqué ici : http://www.gnu.org/savannah-checkout...ata-Structures

    Mais si quelqu'un a une explication sur ce comportement, ça m'intéresse quand même.

    Merci

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. gestion des signaux des touches directionnelles
    Par sedd1991 dans le forum GTK+ avec C & C++
    Réponses: 0
    Dernier message: 01/05/2012, 18h44
  2. gestion des signaux
    Par uriotcea dans le forum Débuter
    Réponses: 6
    Dernier message: 15/01/2010, 10h02
  3. Gestion des signaux
    Par damien77 dans le forum Bibliothèque standard
    Réponses: 12
    Dernier message: 01/03/2008, 22h39
  4. gestion des signaux
    Par pimous dans le forum Linux
    Réponses: 2
    Dernier message: 20/02/2008, 14h44
  5. Gestion des signaux
    Par Kicker dans le forum Administration système
    Réponses: 4
    Dernier message: 23/05/2007, 15h40

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo