0

このプログラムの目的は、新しい子プロセスを fork し、コマンド ライン引数を持つプロセスを実行することです。と入力する/bin/ls --helpと、次のエラーが表示されます。

shadyabhi@shadyabhi-desktop:~/lab/200801076_lab3$ ./a.out
Enter the name of the executable(with full path)/bin/ls --help
Starting the executable as a new child process...
Binary file to be executed: /bin/ls
/bin/ls: unrecognized option '--help
'
Try `/bin/ls --help' for more information.
Status returned by Child process: 2
shadyabhi@shadyabhi-desktop:~/lab/200801076_lab3$

に対する正しい引数は何execve()ですか?

#include<stdio.h>
#include<string.h>      //strcpy() used
#include<malloc.h>      //malloc() used
#include<unistd.h>      //fork() used
#include<stdlib.h>      //exit() function used
#include<sys/wait.h>    //waitpid() used

int main(int argc, char **argv)
{
    char command[256];
    char **args=NULL;
    char *arg;
    int count=0;
    char *binary;
    pid_t pid;
    printf("Enter the name of the executable(with full path)");
    fgets(command,256,stdin);
    binary=strtok(command," ");
    args=malloc(sizeof(char*)*10);
    args[0]=malloc(strlen(binary)+1);
    strcpy(args[0],binary);
    while ((arg=strtok(NULL," "))!=NULL)
    {
        if ( count%10 == 0) args=realloc(args,sizeof(char*)*10);
        count++;
        args[count]=malloc(strlen(arg));
        strcpy(args[count],arg);
    }
    args[++count]=NULL;
    if ((pid = fork()) == -1)
    {
        perror("Error forking...\n");
        exit(1);
    }
    if (pid == 0)
    {
        printf("Starting the executable as a new child process...\n");
        printf("Binary file to be executed: %s\n",binary);
        execve(args[0],args,NULL);
    }
    else
    {
        int status;
        waitpid(-1, &status, 0);
        printf("Status returned by Child process: %d\n",WEXITSTATUS(status));
    }
    return 0;
}
4

3 に答える 3

3

args配列の最初のエントリは、プログラム名である必要があります。コードはプロセス名としてを/bin/ls呼び出します。--help

于 2010-02-02T17:46:36.637 に答える
1

args通話に邪魔されていないことを確認してくださいreallocreallocについてはSOでここを参照してください

編集: また、ループはおかしいように見えます....あなたはstrtokこのように呼びました:

binary = strtok(command、 "");

binary図のように、代わりに使用するようにループ構造を変更します。

char * tmpPtr;
while(binary!= NULL){
   if(count%10 == 0)tmpPtr = realloc(args、sizeof(char)* 10);
   if(tmpPtr!= NULL)args = tmpPtr;
   count ++;
   args [count-1] = malloc(strlen(binary)+1);
   strcpy(args [count-1]、binary);  
   binary = strtok(command、 "");
}

そしてbinary、文字列をコピーするためにを使用します。

これがお役に立てば幸いです、よろしく、トム。

于 2010-02-02T17:46:45.173 に答える
1

あなたのプログラムにはいくつかの明らかなエラーがあります。たとえば、宣言しchar **args=NULL;てからargs=realloc(args,sizeof(char)*10);(これは であるため、 に割り当てるchar**必要があります。いいえchar*?..)。

sizeof(char*)は通常 4 であるのに対し、通常は 1 であるためsizeof(char)、深刻なメモリ管理の問題が発生します (使用する量よりも少ない量を割り当てると、必要のない場所に書き込むことになります)。そこから、すべての地獄が解き放たれ、プログラムの動作が意味を成すとは期待できなくなります。

Valgrindなどのユーティリティを使用してプログラムを実行し、メモリ リークを特定してプログラムを適切に修正することをお勧めします。おそらくexecve、メモリの問題が修正されるとすぐに問題が解消されます。

于 2010-02-02T18:02:32.093 に答える