0

该程序的目的是派生一个新的子进程并执行一个也具有命令行参数的进程。如果我输入/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/lswith--help作为进程名称。

于 2010-02-02T17:46:36.637 回答
1

请检查以确保args没有被realloc电话打扰。请参阅此处关于realloc的 SO

编辑: 循环看起来也很有趣......你strtok这样称呼:

二进制=strtok(命令,“”);

更改循环构造以改为使用binary,如图所示...

字符 *tmpPtr;
而(二进制!= NULL){
   if (count%10 == 0) tmpPtr=realloc(args,sizeof(char)*10);
   如果 (tmpPtr != NULL) 参数 = tmpPtr;
   计数++;
   args[count-1]=malloc(strlen(binary)+1);
   strcpy(args[count-1],二进制);  
   二进制 = strtok(命令,“”);
}

并使用binary复制字符串....

希望这会有所帮助,最好的问候,汤姆。

于 2010-02-02T17:46:45.173 回答
1

你的程序有一些明显的错误。例如,声明char **args=NULL;然后args=realloc(args,sizeof(char)*10);(因为它是char**,你应该分配char*,不是吗?...)。

由于sizeof(char*)通常为 4 而sizeof(char)通常为 1,因此您最终会遇到一些严重的内存管理问题(您分配的内存少于您使用的内存,并且您最终会在不应该写入的地方写入)。从那以后,所有的地狱都崩溃了,你不能指望你的程序的行为有任何意义。

我建议您通过Valgrind之类的实用程序运行您的程序,以找出内存泄漏并适当地纠正程序。execve一旦内存问题得到纠正,您的问题可能就会消失。

于 2010-02-02T18:02:32.093 回答