0

fork()コマンドを使用した後、プロセスが「sonプロセス」に到達しない理由を理解するためにあなたの助けが本当に欲しいです。別のプログラムを実行するプログラムを作成しようとしていますが、そのプログラムは息子のプロセスにさえ到達していないようです。「息子のプロセス」が画面に印刷されていないので、なぜだろうと思います。

これがコードのスケッチです-私が言ったように、それは息子のプロセスにさえ到達していないので、それが大丈夫かどうかさえ確認できません、私はいつも「息子はエラーで終了します」。

#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>



#define MAXARGV 5;

int main() {
    char* cmd;

    int child_status;

    char* s;
    char** argv;
    int counter;

    cmd= (char*) calloc( 5, sizeof(char)*20);
    s=(char*) calloc(1,sizeof(char)*20);
    argv=(char**) calloc(5, sizeof(char*)*20);




    printf("Please write a command\n");

    gets(cmd);

    counter = 0;

    while (strcmp(cmd, "exit") != 0) {

        int pid = fork();


        if (pid == 0) {
            printf("son process");

            while (sscanf(cmd, "%s", s) == 1) {

                strcpy(argv[counter], s);
                counter++;
            }

            execv(argv[0], argv);

            printf("the command is not legal");
            assert(0);

        }

        else {

            if (wait(&child_status) == -1) {
                printf("error waiting for pid=%d\n", pid);
                exit(-1);
            }

              if(WIFEXITED(child_status)!=0)
                    printf("son status=%d\n", WEXITSTATUS(child_status));
                else
                    printf("son exited with error\n");

        }

        printf("Please write a command");

        gets(cmd);

    }

    free(s);
    free(cmd);
    free(argv);
    printf("here as well");
    return 1;
}
4

1 に答える 1

2
  1. プログラムはprintf("son process")問題なく到達しますが、それは文字列をプロセス内のバッファに入れるだけであり、あなたがそれをしなかっfflush()たので、それは画面に表示されず、exec呼び出しでプロセスの残りのメモリとともに破棄されます。stdoutこれは通常ラインバッファリングされているため、そこに改行がある場合は自動フラッシュされることに注意してください。またstderr、デフォルトではバッファリングされておらず、デバッグ印刷に適しています(fprintf(stderr, "child process"))。
  2. の標準入力から読み取ったコマンドをアセンブルしようとしてargvいますが、指定された実際の引数用のメモリしかないため、このメモリをオーバーランしてセグメンテーション違反が発生します。
  3. WIFEXITEDがゼロの場合は、を使用WIFSIGNALEDWTERMSIGて、エラーが実際にSIGSEGVであることを確認する必要があります。
  4. assert(0)エラー後にプロセスを終了するための良い方法ではありません。exit(1)は。アサーションは、コード自体にバグが発生した場合にそれを示す条件に対してのみ使用され、多くの場合NDEBUG、本番コードから(定義することによって)削除されます。
于 2012-11-27T12:07:42.040 に答える